How to check for a leap year in Ruby
Overview
In Ruby, it's simple to check if a year is a leap year. A leap year is a year which occurs every four years. This leap year has 366 days, including 29 days for February.
Just as in the syntax below, we have to know if the year is divisible by 4 without a remainder, and that the year is also divisible by 400 without a remainder. And finally divisible by 100 but with a remainder.
Syntax
if year % 400 == 0# year is a leap yearelsif year % 4 == 0 && year % 100 != 0# year is a leap yearelse# year is not a leap yearend
Example
# create function to check for leap yeardef checkIfLeapYear(year)if year % 400 == 0puts "#{year} is a LEAP YEAR!"elsif year % 100 !=0 && year % 4 == 0puts "#{year} is a LEAP YEAR!"elseputs "#{year} is not a LEAP YEAR!"endend# create some yearsyear1 = 2020year2 = 2022year3 = 2000year4 = 1996year5 = 3004# check if leap yearcheckIfLeapYear(year1)checkIfLeapYear(year2)checkIfLeapYear(year3)checkIfLeapYear(year4)checkIfLeapYear(year5)
Explanation
- Line 2: We create a function
checkIfLeapYear()which takes a year as a parameter, and using the syntax we created, it checks and prints if a year is a leap year. - Lines 13–17: We create some variables with some years as values.
- Lines 20–24: We call the function
checkIfLeapYear()on the years we created.