Like this:
def demo(x)
puts "foo!" if x == 5 || x == 7
end
x == (5 || 7)
won't work because 5 || 7
is 5
, so it's the same as x == 5
.
Вопрос
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.
Решение
Like this:
def demo(x)
puts "foo!" if x == 5 || x == 7
end
x == (5 || 7)
won't work because 5 || 7
is 5
, so it's the same as x == 5
.
Другие советы
To answer your question: No, it's not possible: http://phrogz.net/programmingruby/language.html
Comparison Operators
The Ruby syntax defines the comparison operators ==, ===, <=>, <, <=, >, >=, =~, and the standard methods eql? and equal? (see Table 7.1). All of these operators are implemented as methods. Although the operators have intuitive meaning, it is up to the classes that implement them to produce meaningful comparison semantics. The library reference describes the comparison semantics for the built-in classes. The module Comparable provides support for implementing the operators ==, <, <=, >, >=, and the method between? in terms of <=>. The operator === is used in case expressions, described in the section “Case Expressions”.
So it's a method with only one argument. and (x||y)
will always return x unless, x is false.
Here are some options
... if x == 5 || x == 7
... if [5, 7].include?(x)
... if x.in?(5, 7) # if in rails
It's a little bit of an abuse of case
, but it can make it easy to read, and write, this sort of code:
def demo(x)
case x
when 5, 7
puts "foo!"
end
end
Normally we'd have more when
clauses. The nice thing about this is, it's easy to add more values that x
needs to match:
def demo(x)
case x
when 5, 7, 9..11
puts "foo!"
end
end
[5, 7, 10].each do |i|
demo(i)
end
Running that results in:
foo!
foo!
foo!
Trying to do the same with if
results in visual noise that can obscure the intent of the logic, especially when more tests are added:
case x
when 5, 7, 9..11, 14, 15, 20..30
puts "foo!"
end
Versus:
puts 'foo!' if (x == 5 || x == 7 || x == 14 || x == 15 || 9..11 === x || 20..30 === x)
Or:
puts 'foo!' if (
x == 5 ||
x == 7 ||
x == 14 ||
x == 15 ||
9..11 === x ||
20..30 === x
)