The second version (like most complicated conditions) is error-prone. It's too easy to forget whether you need parentheses or how boolean logic works. The pattern of "is the variable one of these values and if so is this other thing true?" can be especially tricky, so it certainly makes sense to simplify.
However, I don't think the Array class includes contains?
, does it? In my tests, I used include?
:
CONSTANT_1 = 1
CONSTANT_2 = 2
CONSTANT_3 = 3.14
a_boolean = true
var = 3.14
puts "true" if [CONSTANT_1, CONSTANT_2, CONSTANT_3].include?(var) && a_boolean
Notice the parenthesis around var
are necessary so that include?
isn't searching for var && a_boolean
instead of just var
.
The only real problem I see with this idiom is that it would be a bit nicer to have the var
come first. In SQL you might write something like:
var in (CONSTANT_1, CONSTANT_2, CONSTANT_3) and a_boolean
That seems just a little more natural to read.
If you are really worried about efficiency and you do this test many times, it might be better to set up a hash:
constant_test = {}
[CONSTANT_1, CONSTANT_2, CONSTANT_3].each do |k|
constant_test[k] = true
end
puts "true" if constant_test[var] && a_boolean
This has the advantage of being a hash lookup instead of a loop each time you test. (See also: this answer.)