Ruby && 运算符结果没有意义

标签 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

>> 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/

相关文章:

ruby - 使用 key : value instead of :key => value in a hash of Ruby 1. 9 的风格不好吗

ruby - 在 gem 中获取自动加载路径功能

ruby - 从开始救援错误返回一个变量

c++ - 如果 ptr 是指向静态数组第一个元素的 ptr,编译器将如何评估++*ptr++?

c++ - 复制构造函数和赋值运算符

mysql - 如何获取连接中的对象?

ruby-on-rails - 你的 Ruby 版本是 2.3.0,但是你的 Gemfile 指定了 2.1.2

c - 解释一下输出 - 我不明白 i 的值将如何改变

Python 字典 "plus-equal"行为

flutter - 可以用吗??在这种情况下是运营商?