Ruby && Operator Results Don't Make Sense
Here is my code:
>> 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
=> ni开发者_如何学运维l
>> puts "match" if z.upcase.match("APPLE" && "SPOON" && "TREE")
match
=> nil
What I expected to have happen is not get any matches at all. Why do I get matches on y and z?
As dmarkow says, the && operator is for boolean operations, not to give multiple arguments to match().
If you need to find if it matches any of the strings, use some sort of iterator, such as:
puts "MATCH" if ["TREE","SPOON"].any? {|t| z.upcase.match(t)}
Also, since String#match accepts a regular expression, I think you can do a case insensitive regex:
puts "MATCH" if ["TReE","SPoOn"].any? {|t| z.match(/#{t}/i)}
or you could:
puts "MATCH" if z.match(/(tree|spoon)/i)
and since you said you wanted to match all terms:
puts "MATCH" if ["TReE","SPoOn"].all? {|t| z.match(/#{t}/i)}
If the regex confuses you and you want to upcase first:
puts "MATCH" if ["TREE","SPOON"].all? {|t| z.upcase.match(t)}
An &&
statement will either return false, or the last value of the statement:
false && "SPOON"
# => false
"TREE" && "SPOON"
# => "SPOON"
So really, your statements are evaluating the same as this:
puts "match" if y.upcase.match("TREE")
精彩评论