write conditional in ruby

In Ruby, you can use the if statement to write conditionals. The basic syntax for the if statement in Ruby is:

main.rb
if condition
  # code to execute if condition is true
else
  # code to execute if condition is false
end
105 chars
6 lines

Here's an example of how to use the if statement in Ruby:

main.rb
x = 10

if x > 5
  puts "x is greater than 5"
else
  puts "x is not greater than 5"
end
88 chars
8 lines

You can also use elsif to check for additional conditions:

main.rb
x = 10

if x > 10
  puts "x is greater than 10"
elsif x < 10
  puts "x is less than 10"
else
  puts "x is equal to 10"
end
123 chars
10 lines

Additionally, you can use modifiers to write shorter conditional statements. For example:

main.rb
x = 10

puts "x is greater than 5" if x > 5
44 chars
4 lines

This will only output the message if the condition x > 5 is true.

These are the basic ways to write conditionals in Ruby using the if statement. You can combine conditions using logical operators (&& for "and", || for "or") and use comparison operators (>, <, >=, <=, ==, !=) to create more complex conditions.

related categories

gistlibby LogSnag