Conditions
Ruby conditions and switches
#Conditions and Switches# In Ruby, there are various ways to create conditions, use them and write logic. Ruby also provides switch statements in the form of cases that help to simplify logic from time to time.
#Conditions#
Conditions are basically if
, elsif
and else
branching within Ruby. Where it takes a shift from other languages is the convient shorthand approaches to the way to set empty variables and returning the values of an inline conditional statement. Like most languages Ruby also includes a ternary operator.
Example if
, elsif
, else
branching:
my_value = 3
if my_value > 3
// do something amazing
elsif my_value <= 3 && my_value != 0
// do something less amazing
else
// don't really feel up to doing anything amazing
end
If we wanted to shorthand a variable set based on a condition we could write do the following:
my_value = 3
resulting_value = if my_value > 1
"amazing"
else
"not amazing"
end
As you see in the above the result of the condition will set the resulting_value
variable. The last line of the branch will become the return value much the same way the last line of a method becomes a return value.
Ruby provides a simple shorthand way of setting a variable with a null check with the ||=
expression. For instance:
my_map ||= {}
#Switches#
Case statements can be made on any type of value whether a string, int or an object. This is handy to clean up branching when you need too.
Example case statement:
type_value = 'person'
case type_value
when 'person' then
"something for person"
when 'group' then
"something for group"
else
"do the default"
end
You can also use regex expression in the when
conditional check to make your case statement even more terse.
Example regex in case statement:
boolean_str = 'no'
case boolean_str
when /\A(true|t|yes|y|1)\z/ then true
when /\A(false|f|no|n|0)\z/ then false
else false
end
Next: Collection and Loops