one-liner function to check if a year is a leap year in ruby

Here is a one-liner function that checks if a year is a leap year in Ruby:

main.rb
def leap_year?(year)
  year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)
end
81 chars
4 lines

This function takes a year as input and returns true if it is a leap year, and false otherwise. It uses the ternary operator || to evaluate two conditions:

  1. The year must be divisible by 400 for it to be a leap year.
  2. If the year is not divisible by 100, it must be divisible by 4 for it to be a leap year.

Note that this function assumes the year parameter is an integer. If you pass a non-integer value to this function, it may throw an error.

related categories

gistlibby LogSnag