Ruby idiom for default values

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

foo = bar > 0 ? bar : 1


ANSWERS:


Not a generic use case, but:

foo = [bar, 1].max

$ 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".



 MORE:


 ? Name of this idiom? myFont.setWidth(20).setStyle(Style.BOLD).setX().setY().setZ() (...)
 ? Python idiom to return the only element or None
 ? Python idiom to return the only element or None
 ? Python idiom to return the only element or None
 ? Python: if key in dict vs. try/except
 ? Pythonic way to skip items in an iterable?
 ? Pythonic way to skip items in an iterable?
 ? Pythonic way to skip items in an iterable?
 ? Cleanest way to get last item from Python iterator
 ? D3.js: What is the (current) standard way of using force layout?