如何根据Array

时间:2016-07-14 23:33:02

标签: arrays ruby string split

我想基于我在开始时定义为常量的数组来分割字符串:

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"])

我该怎么做?

1 个答案:

答案 0 :(得分: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"] 

请注意,我重新排序OPERATOR的元素,以便'<=''=>'(每个由数组中长度为1的两个字符串组成)位于开头。如果没有这样做,

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

str.split(r)

请参阅Regexp::union