Home Ruby Conditionals: if, else, elseif and unless
Post
Cancel

Ruby Conditionals: if, else, elseif and unless

There is the if statement similar to any other language you came from

1
2
3
4
5
something_evil_lurking_in_the_dark = false

if something_evil_lurking_in_the_dark
  puts "Run away!"
end

Now, let’s negate that

1
2
3
if not something_evil_lurking_in_the_dark
  puts "We are safe!"
end

Ruby has an alternative to if not which is unless

1
2
3
unless something_evil_lurking_in_the_dark
  puts "We are safe!"
end

We can also use the good old else and elseif. While we can use those with unless, it doesn’t make much sense because you can simply reverse your if statement

1
2
3
4
5
if something_evil_lurking_in_the_dark
  puts "Run away..."
else
  puts  "We are safe!"
end

This last example can be written as a one liner, but we will need a new keyword then

1
if something_evil_lurking_in_the_dark then puts "Run away..." else  puts "We are safe!" end

We can write tye same thing using ternary operator

1
something_evil_lurking_in_the_dark ? (puts "Run away..." ): (puts "We are safe!")

Modifier form

Ruby has a modifier form of its conditionals. What that does is reversing the order of the statement to make it more “readable” or rather look like the common English language

1
puts "We are safe!" unless something_evil_lurking_in_the_dark

Even further, we can use the same form with assignment

1
2
message = "We are safe"
message = "Run away!!" if something_evil_lurking_in_the_dark

The value of message will change only if the value of something_evil_lurking_in_the_dark is true.

Conditionals Are Expressions Not Statements

What does that mean?

1
2
some_value = if true then 4 else 6 end
puts some_value # This puts `4`

Yes, if in Ruby evaluate to some value and thus you can do the above. Actually the example where we used puts above can be rewritten as:

1
puts (if something_evil_lurking_in_the_dark then "Run away..." else "We are safe!" end)

or

1
puts something_evil_lurking_in_the_dark ?  "Run away..." :  "We are safe!"

or

1
2
3
4
5
result = if something_evil_lurking_in_the_dark
           "Run away..."
         else
           "We are safe!"
         end

Resources

This post is licensed under CC BY 4.0 by the author.
Contents

Interfaces

Goroutines

Comments powered by Disqus.