[RUBY] Program to find the number of days per month including leap years

【Overview】

1. Conclusion </ b>

2. How to program </ b>

3. Development environment </ b>

  1. Conclusion

Create a method that fits the conditional expression with a remainder (%) of 4,100,400 only in February, and input the date and output the date </ b>!
2. How to program

def get_days_leap_year(year, month)
  each_month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] #---❶
  if month == 2
    if year % 4 == 0
      if year % 100 == 0 && year % 400 != 0 #---❷
        days = 28
      else
        days = 29
      end
    else
      days = 28 #---❸
    end
  else
    days = each_month_days[month - 1] #---❹
  end

  return days #---❺
end

puts "Please enter the year:"
year = gets.to_i
puts "Please enter the month:"
month = gets.to_i #---❻

days = get_days(year, month)
puts "#{year}Year#{month}The moon#{days}There are days" #---❼

❶: Here, the number of days from January to December is put in the array. February is 28th because it is 28th except for leap years. We will select 28 days or 29 days by the conditional formula, and if nothing is true in the conditional formula, it will be 28 days.

❷: It is decided that divisible by 4 = leap year, divisible by 100 = not leap year, 0 divisible by 400 = leap year. I made conditional expressions for "if February" and "if it is divisible by 4". It's easier to understand, and one conditional expression doesn't become complicated, so I've subdivided it. The "divisible by 100 and not divisible by 400" part is collectively described in the conditional expression, and if it applies, it will be 28 days, and if it does not apply (= divisible by 400), it will be 29 days. When determining the leap year, it is written in detail if you search on the net whether it is "4,100,400", so I will omit it here.

❸: If it is not divisible by 4, it is not a leap year, so code a 28-day program for that condition as well.

❹: Since the number starts from "0" peculiar to the array, when you get the array, you can call the number of days of the corresponding month by "Month-1" for the month you want to call. (ex: If it is January, it will be 31st, so [1 (Monday) -1] will be [0] and each_month_days [0], so you can get 31.

❺: The get_days_leap_year method is a method that wants to calculate the number of days, so the return value is days.

❻: The "year" and "month" you want to enter. These are the formal arguments for the get_days_leap_year method.

❼: The year and month used in ❻ are expanded by expression, and the number of days of the get_days_leap_year method is also expanded by # {days}.


3. Development environment

Ruby 2.6.5
Rails 6.0.3.3
Visual Studio Code 1.49.2

Recommended Posts