I want to set a default value if the variable is not set.
Here are valid values (which should not get overwritten):
true
false
0
1
“some string”
Here is how I’m currently trying to do this. Is this the right way?
before_save :set_defaults
def set_defaults
self.is_approved = false if self.is_approved.nil?
end
If this is indeed correct, is there a better syntax? In PHP we had isset() for this sort of stuff.
The idiomatic ruby version for this would be to write:
which would set
is_approvedtofalseifis_approvedisfalsey: that meansnilorfalse. Since setting to false if false is idempotent, it is not wrong.Otherwise you could write:
which is identical to what you wrote:
but I find it slightly more readable.
So yes: that is also the right way to do it.
You will notice that in ruby there are many ways to achieve the same thing. This is the part of programmer happiness: you choose which way suits you the best, and is most expressive at that place (because sometimes one is better suited, and sometimes the other). But for beginners it is sometimes confusing 🙂