Reputation: 1475
I have an array, if I find a value in it, I want to execute a block of code. Also, if the array is nil, I want to execute that block. So the code I tried is:
if !array.respond_to? :index || array.index(str)
#some code
So if it's nil it's true, or if str is somewhere in the array, it's true, right? But if it finds the item at index 0, it doesn't enter the block. Also, according to irb false || 0
evalueates to 0
. WTF?? I thought that everything was true except false and nil. I guess || does something odd that I'm not expecting??
My questions are: What's going on? What's a nice way to write a conditional that does what I want?
Upvotes: 0
Views: 600
Reputation: 160191
if array.nil? || array.member?(s)
# ...
false || 0
evaluates to 0
because it's an or
. False isn't truthy (obviously ;) but 0 is, so the expression is truthy.
Upvotes: 2
Reputation: 12496
Using nil?
and include?
with an inline if
seems most idiomatic to me.
#your code if arr.nil? || arr.include?(str)
Upvotes: 2
Reputation: 4789
if array.nil? || array.member?(str)
#code block
end
The || operator almost reminds you of a coalesce.
Given a = false, b = :bacon
return a || b #returns :bacon
Upvotes: 0
Reputation: 1059
Are you checking for a nil array or an empty one? If you've already declared the array it won't be nil even if it's empty. I'd write it like:
if array.empty? || array.include(str)
or if you really want to check for a nil array:
if array.nil? || array.include(str)
I'd use .include rather than .index to avoid getting a 0.
Upvotes: 0