In addition to the basic programming logic that Ruby has, it also has a few weirder forms of logic it can employ.
Single Line Conditions
Ruby allows for single line conditions where it is almost like a short hand. However, doing so may seem backward to normal logic, because the true block goes first. Consider the following example.
puts "it's even" if 2.even?
This is equivalent to.
if 2.even?
puts "it's even"
end
Even? and Odd?
Notice that we’re using a special method on a primitive numeric data-type to test for even.
If you leave out the ?
(question mark), Ruby gives a nice error message asking if you meant to add it. This makes it fairly easy to learn.
The Ternary Operator
Many languages support the Ternary operator, which is a question mark ( ?
) to check if a condition is true or false. Based upon the condition an true or false block will run.
In most languages/circumstances, you only use this for simple conditions and simple blocks of code.
num1 = 350
num2 = 87
num1 > num2 ? "Greater than" : "Less than"
Notice that it follows a condition ? true block : false block format.
The Unless Operator
While the if statement is good for checking to see if something is true, Ruby has an unless
statement to see if something is not true. This is a little odd, and you could use a not operator (!
).
unless condition
# ...
end
# is equal to
if !condition
# ...
end
Advanced Logic in Ruby was originally found on Access 2 Learn
One Comment
Comments are closed.