I am learning Ruby along with RoR and noticed that instead of using
if !foo
ruby provides
unless foo
In addition, instead of:
while !foo
we have
until foo
Coming from C++/Java, it seems to just confuse me when I read unless/until. Does it seem like people who program a lot in ruby conventionally use unless/until instead of just negating if/while?
Is this something I should just get used to or do you see a lot of variance on the subject?
Thanks!
Yes, using unless condition instead of if !condition is common and idiomatic.
unless foo
# ...
end
It's especially common to use as a post condition:
# Bad
raise "Not Found" if !file_exists?(file_name)
# Good
raise "Not Found" unless file_exists?(file_name)
When in doubt, follow ruby-style-guide
From the syntax section of the ruby style guide:
Favor unless over if for negative conditions (or control flow ||).
# bad
do_something if !some_condition
# bad
do_something if not some_condition
# good
do_something unless some_condition
# another good option
some_condition || do_something
And
Favor until over while for negative conditions.
# bad
do_something while !some_condition
# good
do_something until some_condition
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With