Joe Essey Joe Essey - 2 months ago 10
Ruby Question

Conditional assignment in Ruby

I'm working on a project with several instances of the following pattern that I am not familiar with. I don't know what to call it so I can't find any docs on it. What is the following concept?

if !@two = [nil, 2].sample
puts 'there was an error'
else
puts @two
end


Thanks

Answer

It basically leans on Ruby's falsy objects: nil and false.

Everything except for nil and false is said to be truthy in Ruby.

So in the example it prints the value of @two if it's truthy (2), otherwise (nil) it prints the error message.

I do not think this "concept" has a name.