Ruby - Check If a Number is Even or Odd

1. Introduction

In mathematics and computer science, integers are classified as either even or odd. An even number is divisible by 2 with no remainder, while an odd number leaves a remainder of 1 when divided by 2. In this guide, we'll walk through a simple Ruby program that determines whether a given number is even or odd.

2. Program Steps

1. Set up your Ruby development environment.

2. Prompt the user to input an integer.

3. Use a conditional statement to determine if the number is even or odd.

4. Display the result to the user.

3. Code Program

# Prompt the user for an integer input
puts "Please enter an integer:"
number = gets.chomp.to_i
# Check if the number is even or odd and display the result
if number % 2 == 0
  puts "#{number} is an even number."
else
  puts "#{number} is an odd number."
end

Output:

Please enter an integer:
7
7 is an odd number.

Explanation:

1. puts: This command displays messages to the console, which in this case, is used to ask the user for an input.

2. gets: A method to capture user input. The input is read as a string by default.

3. chomp: This string method removes the newline character which gets appended when the user presses Enter.

4. to_i: This method converts the captured string input to an integer.

5. number % 2 == 0: Here we utilize the modulo operator % which returns the remainder of a division. If the remainder is 0 when a number is divided by 2, then the number is even; otherwise, it's odd.


Comments