if/else statements allow you to execute different blocks of code depending on whether a condition is true or false. Here are three examples of how to use them:
.jpg)
Example 1: Checking if a Number is Positive or Negative
print "Enter a number: " number = gets.chomp.to_i if number > 0 puts "#{number} is positive" else puts "#{number} is negative" end
In this example, the user is prompted to enter a number. The program then checks if the number is greater than 0 using the if keyword. If the number is greater than 0, the program prints that the number is positive. Otherwise, the program prints that the number is negative using the else keyword.
Example 2: Checking if a String is Empty
print "Enter a string: " string = gets.chomp if string.empty? puts "The string is empty" else puts "The string is not empty" end
In this example, the user is prompted to enter a string. The program then checks if the string is empty using the if keyword. If the string is empty, the program prints that the string is empty. Otherwise, the program prints that the string is not empty using the else keyword.
Example 3: Checking if a Number is Even or Odd
print "Enter a number: " number = gets.chomp.to_i if number % 2 == 0 puts "#{number} is even" else puts "#{number} is odd" end
In this example, the user is prompted to enter a number. The program then checks if the number is even or odd using the % operator and the if keyword. If the number is even, the program prints that the number is even. Otherwise, the program prints that the number is odd using the else keyword.
0 Comments