Joe Essey
Joe Essey

Reputation: 3527

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

Upvotes: 1

Views: 562

Answers (3)

user229044
user229044

Reputation: 239250

The practice of using the value of an assignment expression in a conditional doesn't really have a name, per se, but the practice of wrapping the assignment in parenthesis is called "Safe assignment in condition", which is something you should adopt if you're writing code like this.

Upvotes: 1

Stefan
Stefan

Reputation: 114138

Nothing special here, it's equivalent to:

@two = [nil, 2].sample

if !@two
  puts 'there was an error'
else
  puts @two
end

@two = [nil, 2].sample returns a random element from [nil, 2], i.e. either nil or 2, and assigns it to the instance variable @two.

The conditional should be self-explanatory.

Upvotes: 1

Andrey Deineko
Andrey Deineko

Reputation: 52357

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.

Upvotes: 2

Related Questions