Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convention: if (!foo) vs unless (foo). And while (!foo) vs until (foo) [closed]

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!

like image 751
mharris7190 Avatar asked Mar 18 '26 16:03

mharris7190


2 Answers

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

like image 121
meagar Avatar answered Mar 20 '26 06:03

meagar


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
like image 23
allonhadaya Avatar answered Mar 20 '26 06:03

allonhadaya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!