0

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?

7
  • You just said it yourself: "I thought that everything was true except false and nil." So why are you surprised that false || 0 is 0? Commented Nov 2, 2011 at 19:57
  • I'm surprised that false || 0 != true. 0 isn't false or nil, so that should be false || true = true. Why isn't it? Commented Nov 2, 2011 at 20:07
  • @pseudopeach Because 0 is truthy, and that's how Ruby works. Commented Nov 2, 2011 at 20:24
  • 1
    @Dave Newton "Truthy" is obviously ill-defined for the poster. Perhaps you would do better to define and explain, instead of saying "that's how Ruby works." Commented Nov 3, 2011 at 14:25
  • @Andy_Vulhop It was explained yesterday; redundant. Commented Nov 3, 2011 at 14:26

4 Answers 4

2

Using nil? and include? with an inline if seems most idiomatic to me.

#your code if arr.nil? || arr.include?(str) 
Sign up to request clarification or add additional context in comments.

5 Comments

I like your code better, but I still don't get why false or 0 is 0.
@pseudopeach A Ruby "or" will return the first truthy value it finds, in this case, 0.
A 'truthy' expression is true in a boolean context.
Specifically, in Ruby, everything but false and nil is truthy.
So if (false || 0) is truthy, why didn't my IF block execute?
2
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.

Comments

0

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.

Comments

0
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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.