dooche
dooche

Reputation: 483

Ruby idiom for default values

Is there a better way to write this in Ruby, without writing "bar" twice?

foo = bar > 0 ? bar : 1

Upvotes: 1

Views: 239

Answers (2)

drharris
drharris

Reputation: 11214

Not a generic use case, but:

foo = [bar, 1].max

Upvotes: 4

miku
miku

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

Related Questions