Rudi Dykman
Rudi Dykman

Reputation: 23

Ruby - combination of if and unless on one line

I've run into a line of code that combines the use of if and unless in a way I've never encountered before:

return foo if condition_a unless condition_b

My expectation is that this is equivalent to:

unless condition_b
  if condition_a
    return foo
  end
end

Is that correct?

Upvotes: 1

Views: 187

Answers (1)

pamit
pamit

Reputation: 332

Yes, those expressions are the same. The first one is not so readable and not so common as it can be confusing:

irb(main):016:0> condition_a = true
irb(main):017:0> condition_a = true
irb(main):018:0> condition_b = false
irb(main):019:0> foo = 'foo'
irb(main):020:0> p foo if condition_a unless condition_b
"foo"
=> "foo"
irb(main):021:0> condition_b = true
irb(main):022:0> p foo if condition_a unless condition_b
=> nil
irb(main):023:0> condition_a = false
irb(main):024:0> condition_b = false
irb(main):025:0> p foo if condition_a unless condition_b
=> nil
irb(main):026:0>

Upvotes: 1

Related Questions