Using ||
is the only syntax that is DRY using basic Ruby. However this won't work:
- if you want to reject
var1
when it's in a truthy state, e.g. ""
- if you want to keep
var1
when it's in a falsy state, e.g. false
(which is different for your purposes to nil
)
In short if your aim is to check whether var1
is present, you will have to repeat yourself with some kind of var1.check ? var1 : var2
syntax. (check
isn't a real method – I'm using that to mean whatever check you want to do on it to ensure it's present for your app's purposes.)
The Demand gem which I wrote gets around this and allows a DRY syntax:
return demand(var1, var2)
This checks whether var1
is present and returns it if so. Otherwise, it returns var2
.