user1713964
user1713964

Reputation: 1249

Can we do `a = b || c` in Ruby?

I would like to know if we can express "if the first is null, then choose the second."

foo = bar || doe 
#if bar is nil, foo = doe

Upvotes: 2

Views: 784

Answers (2)

Radek Paviensky
Radek Paviensky

Reputation: 8486

Sure. It works as expected:

bar = nil
doe = "Hello"
foo = bar || doe
# => "Hello"

Upvotes: 5

Almaron
Almaron

Reputation: 4147

well, yea. a ||= b is the equivalent of a = a || b if the first element is nil or false then the result is the second element.

Upvotes: 4

Related Questions