Reputation: 483
Is there a better way to write this in Ruby, without writing "bar" twice?
foo = bar > 0 ? bar : 1
Upvotes: 1
Views: 239
Reputation: 188054
$ irb
>> x ||= "default"
=> "default"
>> x ||= "nothing changes, since x has been defined"
=> "default"
The value of x will be replaced with "default", but only if x is nil or false. So I am not sure it fits your use case (x > 0)
.
x ||= "default"
is just a shorthand for x || x = "default"
.
Upvotes: 3