0

I want to split a string based on an array that I define as a constant at the start:

class Query
  OPERATOR = [':','=','<','>','<=','>=']
  def initialize(params)
    #Here i want to split given params if it contains any
    #of the operators from OPERATOR     
  end
end

Query.new(["Status<=xyz","Org=abc"])

How can I do this?

1
  • When asking about a problem with your code it's helpful if you provide the sample input and expected output. If we build our own input and output expectations we won't necessarily match the criteria you have. Read "minimal reproducible example". Also, while you provide a shell, you don't show any attempt to solve the problem. It's really important you show us what you tried and explain why it didn't work. Failing to do that makes it look like you want us to write the code for you. Commented Jul 15, 2016 at 1:23

1 Answer 1

3
OPERATOR = ['<=','=>',':','=','<','>']

r = /\s*#{ Regexp.union(OPERATOR) }\s*/
  #=> /\s*(?-mix:<=|=>|:|=|<|>)\s*/

str = "Now: is the =time for all <= to =>"

str.split(r)
  #=> ["Now", "is the", "time for all", "to"] 

Note that I reordered the elements of OPERATOR so that '<=' and '=>' (each comprised of two strings of length one in the array) are at the beginning. If that is not done,

OPERATOR = [':','=','<','>','<=','>=']
r = /\s*#{ Regexp.union(OPERATOR) }\s*/
  #=> /\s*(?-mix::|=|<|>|<=|>=)\s*/ 
str.split(r)
  #=> ["Now", "is the", "time for all", "", "to"] 

str.split(r)

See Regexp::union.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks that works but with one small problem. See output below. Seems like where it encounters <= or >= it actually adds an empty newline. Now is the time for all to
Thanks. It does still show white spaces but i am sure i will figure that out.
I didn't know you wanted to remove the spaces. I fixed it so that it would.
You sir are a legend. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.