我想基于我在开始时定义为常量的数组来分割字符串:
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"])
我该怎么做?
答案 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。