0

I'm trying to get the == operator to match two possible values like so.

def demo(x)
  puts "foo!" if x == (5 || 7)
end

demo(5)
#=> "foo!"
demo(7)
#=> nil

So this doesn't work, but is there a way to match multiple values at the end of a == operator in ruby? I think I've seen it done before, so that's why I tried it, but I'm not sure about that.

4

4 回答 4

3

像这样:

def demo(x)
  puts "foo!" if x == 5 || x == 7
end

x == (5 || 7)不起作用,因为5 || 7is 5,所以它与x == 5.

于 2013-11-08T16:49:23.673 回答
2

这里有一些选项

... if x == 5 || x == 7
... if [5, 7].include?(x)
... if x.in?(5, 7) # if in rails
于 2013-11-08T16:49:05.337 回答
2

回答你的问题:不,这是不可能的:http: //phrogz.net/programmingruby/language.html

比较运算符

Ruby 语法定义了比较运算符 ==、===、<=>、<、<=、>、>=、=~ 和标准方法 eql? 和平等?(见表 7.1)。所有这些运算符都作为方法实现。尽管运算符具有直观的含义,但要由实现它们的类来产生有意义的比较语义。库参考描述了内置类的比较语义。模块 Comparable 提供对实现运算符 ==、<、<=、>、>= 和之间的方法的支持?在 <=> 方面。运算符 === 用于案例表达式,在“案例表达式”一节中进行了描述。

所以这是一种只有一个参数的方法。并且(x||y)将始终返回 x,除非 x 为假。

于 2013-11-08T17:00:38.727 回答
1

这有点滥用case,但它可以使这种代码易于阅读和编写:

def demo(x)
  case x
  when 5, 7
    puts "foo!"
  end
end

通常我们会有更多的when子句。x这样做的好处是,添加更多需要匹配的值很容易:

def demo(x)
  case x
  when 5, 7, 9..11
    puts "foo!"
  end
end

[5, 7, 10].each do |i|
  demo(i)
end

运行结果:

foo!
foo!
foo!

尝试对if结果做同样的事情会导致视觉噪音,这可能会掩盖逻辑的意图,尤其是在添加更多测试时:

case x
when 5, 7, 9..11, 14, 15, 20..30
  puts "foo!"
end

相对:

puts 'foo!' if (x == 5 || x == 7 || x == 14 || x == 15 || 9..11 === x || 20..30 === x)

或者:

puts 'foo!' if (
  x == 5  ||
  x == 7  ||
  x == 14 ||
  x == 15 ||
  9..11  === x ||
  20..30 === x
)
于 2013-11-08T18:41:26.220 回答