这是我的代码:
>> x = "apple spoon"
=> "apple spoon"
>> y = "spoon tree"
=> "spoon tree"
>> z = "apple tree"
=> "apple tree"
>> puts "match" if x.upcase.match("APPLE" && "SPOON" && "TREE")
=> nil
>> puts "match" if y.upcase.match("APPLE" && "SPOON" && "TREE")
match
=> nil
>> puts "match" if z.upcase.match("APPLE" && "SPOON" && "TREE")
match
=> nil
我期望发生的是根本没有得到任何匹配项。为什么我在 y 和 z 上得到匹配?
最佳答案
正如 dmarkow 所说,&& 运算符用于 bool 运算,而不是为 match() 提供多个参数。
如果您需要查找它是否与任何字符串匹配,请使用某种迭代器,例如:
puts "MATCH" if ["TREE","SPOON"].any? {|t| z.upcase.match(t)}
此外,由于 String#match 接受正则表达式,我认为您可以做一个不区分大小写的正则表达式:
puts "MATCH" if ["TReE","SPoOn"].any? {|t| z.match(/#{t}/i)}
或者你可以:
puts "MATCH" if z.match(/(tree|spoon)/i)
既然你说你想匹配所有的词:
puts "MATCH" if ["TReE","SPoOn"].all? {|t| z.match(/#{t}/i)}
如果正则表达式让你感到困惑,而你想先大写:
puts "MATCH" if ["TREE","SPOON"].all? {|t| z.upcase.match(t)}
关于Ruby && 运算符结果没有意义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6192311/