The following code causes an argument error:
n = 15
(n % 4 == 0)..(n % 3 == 0)
# => bad value for range (ArgumentError)
which I think is because it evaluates to:
false..true
and different types of classes are used in range: TrueClass
and FalseClass
. However, the following code does not raise an error. Why is that? Does Enumerable#collect
catch it?
(11..20).collect { |i| (i % 4 == 0)..(i % 3 == 0) ? i : nil }
# => no error
Added later: If fcn returns 15, then only first half of range is evaluated
def fcn(x)
puts x
15
end
if (fcn(1) % 4 == 0)..(fcn(2) % 3 == 0); end
# => 1
but if we change return value to 16 then input will be
# => 1
# => 2
It's strange, because in this case expression evaluates to
true..false
And such kind of range is invalid according to sawa's answer below.
Then in first case (with def's return value 15) we have only partial range with no ending part? It's so strange :)
(true..false); 1
works butx = (true..false); 1
does not? btw, this does not happen with Ruby 1.8.7. – Applewhite