红宝石&&运算符结果没有意义
这是我的代码:
>> 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 上得到匹配项?
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
=> nil
>> 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如 dmarkow 所说, &&运算符用于布尔运算,而不是为 match() 提供多个参数。
如果您需要查找它是否与任何字符串匹配,请使用某种迭代器,例如:
另外,由于 String#match 接受正则表达式,我认为您可以执行不区分大小写的正则表达式:
或者您可以:
并且因为您说你想匹配所有术语:
如果正则表达式让你感到困惑并且你想首先大写:
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:
Also, since String#match accepts a regular expression, I think you can do a case insensitive regex:
or you could:
and since you said you wanted to match all terms:
If the regex confuses you and you want to upcase first:
&&
语句将返回 false,或者返回该语句的最后一个值:实际上,您的语句的计算结果与此相同:
An
&&
statement will either return false, or the last value of the statement:So really, your statements are evaluating the same as this: