Difference - Unless/If

Difference - unless / if

unless is just a negated if. That is, it executes whatever it contains if the condition is not true.

unless foo?
# blabla
end

Simply means

if !foo?
# blabla
end

It's all a matter of what you find easier to read, really.

See also: Unless, The Abused Ruby Conditional

Ruby: unless vs if not

I hope this helps you: https://github.com/rubocop-hq/ruby-style-guide#if-vs-unless

Prefer 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

I personally agree with what's written there choosing unless something over if !something for modifiers and simple ones and when there's an else prefer if.

Ruby unless vs if logic

In your second example, once result is set to true, nothing ever sets it to false again. So if the first value yielded from my_each is truthy, then the my_all? method will return true.

This second example seems like more like an implementation of any?, rather than all?. Except it is actually only checking the first element. If the first i is falsey, then the loop will be broken and it will return false. If the first i is truthy, then it will be set to true and nothing will set it back to false, and the method will return `true.

See these two examples, where the only difference is the values yielded by my_each:

  • Returns true (first value is truthy)
  • Returns false (first value is falsey)

How to convert this if condition to unless?

Regarding your comment:

I'm asking this question because of this lint error

Use a guard clause instead of wrapping the code inside a conditional expression

This means that instead of:

def foo(array)
if array.present?
puts "hello"
end
end

You are supposed to use:

def foo(array)
return unless array.present?
puts "hello"
end

See https://github.com/bbatsov/ruby-style-guide#no-nested-conditionals

If this is a Rails question (is it?), you can also use blank?:

def foo(array)
return if array.blank?
puts "hello"
end

if/unless modifiers vs. and/or

Alternatives that I would choose (and have used) when this issue arises:

if x=a[2]
n = 3*(x**2) + 4*x + 5
end

if x=a[2] then n = 3*(x**2) + 4*x + 5 end

x=nil
n = 3*(x**2) + 4*x + 5 if x=a[2]

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

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



Related Topics



Leave a reply



Submit