Ruby - Check Leap Year

1. Introduction

A leap year occurs almost every four years to account for the fact that Earth's orbit around the sun takes approximately 365.24 days. A leap year has 366 days, with an additional day added to February. Determining whether a year is a leap year or not involves some specific rules. In this tutorial, we'll create a Ruby program to check if a given year is a leap year.

2. Program Steps

1. Set up the Ruby development environment.

2. Prompt the user to input a year.

3. Check the year against the leap year conditions.

4. Display the result to the user.

3. Code Program

# Prompting the user for a year
puts "Enter a year to check if it's a leap year:"
year = gets.chomp.to_i
# Checking if the year is a leap year
if (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0)
  puts "#{year} is a leap year."
  puts "#{year} is not a leap year."


Enter a year to check if it's a leap year:
2000 is a leap year.


1. gets: Captures user input, which is read as a string by default.

2. chomp: Removes the newline character, which is added when the user hits Enter.

3. to_i: Converts the string input to an integer for arithmetic operations.

4. year % 4 == 0: Checks if the year is divisible by 4, which is one of the conditions for a leap year.

5. year % 100 != 0: Ensures that the year is not divisible by 100 unless it is also divisible by 400. This rule accounts for the fact that Earth's orbit is not exactly 365.25 days long.

6. year % 400 == 0: Ensures that years divisible by 400 are considered leap years. This rule helps adjust for the discrepancy introduced by the previous rule.

7. The combination of the above conditions using && (and) and || (or) allows us to correctly determine leap years in the Gregorian calendar.

By following these steps, we can determine whether a given year is a leap year using Ruby.