Conditionals in Ruby
In Ruby, conditions are essential to control the flow of execution of your program. There are different structures to evaluate conditions and execute different actions based on the result.
if: Link to heading
- Used to execute a block of code if a condition is met.
- The condition is evaluated in parentheses.
- If the condition is true, the code block is executed.
- If the condition is false, the code block is ignored.
Example: Link to heading
is_authenticated = true
if is_authenticated
puts "Admin section"
else
puts "Login section"
end
elsif: Link to heading
- Used to evaluate an alternative condition if the if condition is not met.
- Multiple elsifs can be nested to evaluate multiple conditions.
Example: Link to heading
role = :user
if role == :admin
puts "Admin section"
elsif role == :superadmin
puts "Superadmin section"
else
puts "Login section"
end
unless: Link to heading
- It is an alternative form of if that executes the code block if the condition is false.
- It can be useful for writing more intuitive code.
Example: Link to heading
unless is_authenticated
puts "Login section"
else
puts "Admin section"
end
case: Link to heading
- Used to evaluate a variable against a series of values and execute the code associated with the first value that matches.
- It can be useful to handle multiple options efficiently.
Example: Link to heading
day = "Monday"
case day
when "Monday"
puts "Today we have a lot of work."
when "Tuesday"
puts "Meeting at 10:00 am."
when "Wednesday"
puts "Programming lessons in afternoon."
else
puts "Weekend, ¡please rest!"
end
Comparison operators: Link to heading
- == : Same
- != : Different
- >= : Greater than or equal to
- <= : Less than or equal to
- > : Greater than
- < : Less than
Example: Link to heading
number = 10
if number >= 10
puts "The number is greater than or equal to 10."
else
puts "The number is less than 10."
end
In summary, conditional structures allow you to control the flow of your program and execute different actions depending on the conditions that are met. It is important to choose the appropriate structure for each case and use the correct comparison operators to evaluate the conditions.
Keep learning about conditional structures to master the flow of your code in Ruby!
Additional Tips: Link to heading
- You can use nesting of if and elsif to evaluate more complex conditions.
- You can use the && operator to combine two conditions and the || operator to evaluate two conditions as one.
- Can you use the nil? method to check if a value is nil.
Example: Link to heading
number = 10
if number > 0 && number < 100
puts "The number is between 0 and 100."
elsif number == 0
puts "The number is 0."
else
puts "The number is outside the range 0-100."
end
if number.nil?
puts "The number has no value."
else
puts "The number is #{number}."
end
Keep experimenting with conditional structures to create more robust and flexible programs!