Ruby better ternary conditional (DRY)

  • A+
Category:Languages

Is there a way to avoid the redondance on this expression :

something = find_something(id) ? find_something(id) : create_something(foo) 

find_something(id) is called twice. This is a smell that I want to avoid.

Remark

find_something return a NilClass (nil) if nothing is found.

 


Anything like this?

something = find_something(id) || create_something(foo) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: