There is the if statement similar to any other language you came from
something_evil_lurking_in_the_dark = false
if something_evil_lurking_in_the_dark
puts "Run away!"
endNow, let’s negate that
if not something_evil_lurking_in_the_dark
puts "We are safe!"
endRuby has an alternative to if not which is unless
unless something_evil_lurking_in_the_dark
puts "We are safe!"
endWe 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
if something_evil_lurking_in_the_dark
puts "Run away..."
else
puts "We are safe!"
endThis last example can be written as a one liner, but we will need a new keyword then
if something_evil_lurking_in_the_dark then puts "Run away..." else puts "We are safe!" endWe can write tye same thing using ternary operator
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
puts "We are safe!" unless something_evil_lurking_in_the_darkEven further, we can use the same form with assignment
message = "We are safe"
message = "Run away!!" if something_evil_lurking_in_the_darkThe 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?
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:
puts (if something_evil_lurking_in_the_dark then "Run away..." else "We are safe!" end)or
puts something_evil_lurking_in_the_dark ? "Run away..." : "We are safe!"or
result = if something_evil_lurking_in_the_dark
"Run away..."
else
"We are safe!"
end
Comments powered by Disqus.