Junaid
Junaid

Reputation: 603

How to split string based on pre-defined values from Array

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?

Upvotes: 0

Views: 58

Answers (1)

Cary Swoveland
Cary Swoveland

Reputation: 110755

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.

Upvotes: 3

Related Questions