Ruby&&;运算符结果不';没有道理
这是我的密码:Ruby&&;运算符结果不';没有道理,ruby,operators,Ruby,Operators,这是我的密码: >> 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 >&
>> 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上找到匹配项 一个
&&
语句要么返回false,要么返回语句的最后一个值:
false && "SPOON"
# => false
"TREE" && "SPOON"
# => "SPOON"
因此,实际上,您的陈述的评估结果与此相同:
puts "match" if y.upcase.match("TREE")
正如dmarkow所说,&&运算符用于布尔运算,而不是提供多个参数来匹配() 如果需要查找它是否匹配任何字符串,请使用某种迭代器,例如:
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)}
事实上,我正在努力做到这一切。我能做什么吗?全部?是的,全部?是另一种适用于枚举的方法。如果z.upcase.match(“树”、“勺子”、“苹果”),则放上“match”。诸如此类?这不管用,但这正是我想要的主意。谢谢。我试图弄清楚如何在不干扰regex的情况下完成它。match主要是一个regex函数。在上一个示例中,我认为可以将
match
更改为include?