[Ruby] Leap year judgment program

Overview

I wrote a program that outputs the year and month. You need to consider the leap year at that time.

table of contents

--Leap year

--Practice --Problem --Conditions

--Answer

--Supplement

--References

Leap year

Leap years can be determined under the following conditions.

-① When the Christian era is divisible by 4 ――② However, when it is divisible by 100, it is a normal year. ―― ③ However, if it is divisible by 400, it is a leap year.

Practice

problem

Enter the year and month and write a program to find the number of days in that month.

conditions

--Please consider the leap year

answer

def leap_year?(year, month)
  #Number of days in each month
  month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
  #Get days from array
  days = month_days[month - 1]

  #February
  if month == 2
    #Condition ① When it is divisible by 4
    if year % 4 == 0
      #Condition ②,③ When the Christian era is divisible by 100 and not divisible by 400
      if year % 100 == 0 && year % 400 != 0
        days      #Not a leap year
      else
        days + 1  #28th+1 Then it will be 29 days
      end
    #If it's not divisible by 4, it's not a leap year
    else
      days
    end

  #Other than February
  else
    days
  end
end

#Enter the year
p 'Please enter the year'
year = gets.to_i

#Enter month
p 'Please enter the month'
month = gets.to_i

#Method call
days = leap_year?(year, month)
p "#{year}Year#{month}The moon#{days}There are days"

Supplement

② However, if it is divisible by 100, it is normal. ③ However, if it is divisible by 400, it is a leap year.

In the above answer, such a condition

year % 100 == 0 && year % 400 != 0

It is described like this.

If it is a leap year ** when it is divisible by ** 400, it is a normal year ** if it is not divisible by ** 400. Taking advantage of this, ** else (otherwise) will have a leap year **.

References

-Free encyclopedia "Wikipedia" (leap year)

-Ruby 3.0.0 Reference Manual (Date # leap?)

Recommended Posts

[Ruby] Leap year judgment program
Leap year judgment with Ruby
Ruby payroll program
Bingo judgment program
Ruby score calculation program
Ruby Numeric Reference Program
Program to determine if it is a leap year
Use C program from Ruby
Judgment of fractions in Ruby
ruby Exercise Memo III (if, case, array, each by leap year)
Ruby: I made a FizzBuzz program!