DEV Community

Burdette Lamar
Burdette Lamar

Posted on

Ruby Conditionals Return Values: Use Them!

Ruby conditionals return values. That is, a Ruby conditional such as if or case is an expression that returns a value.

You can use these values to simplify your code.

The examples below use the Interactive Ruby Shell, irb.

If-Else

Assume that these are defined:

def some_condition; true; end
def an_expression_that_returns_a_value; 0; end
def another_expression_that_returns_a_value; 1; end
Enter fullscreen mode Exit fullscreen mode

This:

if some_condition
  q = an_expression_that_returns_a_value
else
  q = another_expression_that_returns_a_value
end
# => 0
q
# => 0
Enter fullscreen mode Exit fullscreen mode

Can use the return value to become this:

q = if some_condition
      an_expression_that_returns_a_value
    else
      another_expression_that_returns_a_value
    end
# => 0
q
# => 0
Enter fullscreen mode Exit fullscreen mode

Of course in this case the ternary operator would suffice, but it can be harder to read:

q = some_condition ?
      an_expression_that_returns_a_value :
      another_expression_that_returns_a_value
# => 0
q
# => 0
Enter fullscreen mode Exit fullscreen mode

If-Elsif-Else

Now assume further that these are also defined:

def some_other_condition; false; end
def yet_another_expression_that_returns_a_value; 2; end
Enter fullscreen mode Exit fullscreen mode

This:

if some_condition
  q = an_expression_that_returns_a_value
elsif some_other_condition
  q = another_expression_that_returns_a_value
else
  q = yet_another_expression_that_returns_a_value
end
# => 0
q
# => 0
Enter fullscreen mode Exit fullscreen mode

Can use the return value to become this:

q = if some_condition
      an_expression_that_returns_a_value
    elsif some_other_condition
      another_expression_that_returns_a_value
    else
      yet_another_expression_that_returns_a_value
    end
# => 0
q
# => 0
Enter fullscreen mode Exit fullscreen mode

Case

This:

case
  when some_condition
    q = an_expression_that_returns_a_value
  when some_other_condition
    q = another_expression_that_returns_a_value
  else
    q = yet_another_expression_that_returns_a_value
  end
# => 0
q
# => 0
Enter fullscreen mode Exit fullscreen mode

Can use the return value to become this:

q = case
    when some_condition
      an_expression_that_returns_a_value
    when some_other_condition
      another_expression_that_returns_a_value
    else
      yet_another_expression_that_returns_a_value
    end
# => 0
q
# => 0
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
rnrnshn profile image
Olimpio

Very interesting... Thanks. I will spent some time figuring this out...