Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 65 / 68

Checking Whether a Year Is a Leap Year

In this lesson you will learn the leap-year rule and see how to turn a deceptively simple rule with hidden exceptions into correct code. This is for anyone searching for "Ruby leap year check".

A year is a leap year if it is divisible by 4 but not by 100, or if it is divisible by 400. It is basic logic that appears in calendar and date-calculation programs.

The sample code decides it with the single expression (year % 4 == 0 && year % 100 != 0) || year % 400 == 0. The famous examples are 2000, which is divisible by 400 and so is a leap year, and 1900, which is divisible by 100 but not 400 and so is not.

A common stumbling block for beginners is overlooking the exception for years divisible by 100. Implement only "divisible by 4 means leap year" and a year like 1900 gets wrongly reported as one.

The fact that a plain "multiple of 4" test is wrong makes this a classic exercise in assembling conditions correctly. It is foundational knowledge for date-driven programs such as calendar apps and age calculations.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)