Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

How to check for a leap year in Ruby

okwudili onyejiaku

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 year
elsif year % 4 == 0 && year % 100 != 0
    # year is a leap year
else 
    #   year is not a leap year
end
Syntax to check if a year is Leap year or not

Example

# create function to check for leap year
def checkIfLeapYear(year)
  if year % 400 == 0
	  puts "#{year} is a LEAP YEAR!"
  elsif year % 100 !=0 && year % 4 == 0 
	  puts "#{year} is a LEAP YEAR!"
  else
	  puts "#{year} is not a LEAP YEAR!"
  end
end

# create some years
year1 = 2020
year2 = 2022
year3 = 2000
year4 = 1996
year5 = 3004

# check if leap year
checkIfLeapYear(year1)
checkIfLeapYear(year2)
checkIfLeapYear(year3)
checkIfLeapYear(year4)
checkIfLeapYear(year5)
Code to check if a year is leap year or not in Ruby

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.

RELATED TAGS

ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring