LoginSignup
1
0

More than 5 years have passed since last update.

Rubyで年と月を入力してその月が何日あるのか判定するプログラム

Last updated at Posted at 2017-12-24

単純なプログラムですがメゾット、配列、引数、条件分岐、返り値、式展開、あといろいろ学べます。

days.rb
def get_days(year,month)
days_list = [31,28,31,30,31,30,31,31,30,31,30,31]
    if month == 2 && (year % 400 == 0 || year%4 == 0 && year % 100 != 0 )
       return 29
     else
       return days_list[month -1]
    end
end
puts "西暦を入力してね"
input_year = gets.to_i
puts "月を入力してね"
input_month = gets.to_i
days =get_days(input_year,input_month)
puts "#{input_year}#{input_month}月は#{days}日間あります"

うるう年の条件

(1)西暦年号が4で割り切れる年をうるう年とする。

(2)(1)の例外として、西暦年号が100で割り切れて400で割り切れない年は平年とする。

まず1月から12月までの各月の日の数を配列に入れます。このときの2月は平年(28日)です。配列のインデックス番号はゼロから始まるので注意。
次のif文は2月でうるう年の時に29を返しています

構文解説

def get_days(year,month)のyearとmonthは変数です。仮引数ともいいます。
days_list = [31,28,31,30,31,30,31,31,30,31,30,31]は配列です。12個の要素を持っています。days_list[0]は31の要素です。

参考

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0