红宝石&&运算符结果没有意义

发布于 2024-11-10 10:41:07 字数 530 浏览 2 评论 0原文

这是我的代码:

>> 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

注定孤独终老 2024-11-17 10:41:07

正如 dmarkow 所说, &&运算符用于布尔运算,而不是为 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)}

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)}
痴情 2024-11-17 10:41:07

&& 语句将返回 false,或者返回该语句的最后一个值:

false && "SPOON"
# => false
"TREE" && "SPOON"
# => "SPOON"

实际上,您的语句的计算结果与此相同:

puts "match" if y.upcase.match("TREE")

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")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文