3
1

More than 3 years have passed since last update.

Rubyでうるう年判定

Last updated at Posted at 2020-12-29

!macOS-11.1 !ruby-2.7.2p137

Preface (はじめに)

本記事はマルチスケールシミュレーション特論の第7回に関連する記事です.チャート式Rubyに従って進めていきます.

今回はチャート式ruby-III(if, case, Array.each by leap year)に従ってRubyの条件分岐とArray.eachについて学んでいきます.

Ruby

条件分岐

if-elsif-else-end

ifは条件が成立した節の最後に評価した式の結果を返します. [ ]は省略可能な部分です.

if  [then]
   ...
[elsif  [then]
   ... ]
...
[else 
   ... ]
end

Rubyでは, falseまたはnilだけが偽, それ以外は0や空文字含めすべて真となります.

条件演算子

さらにサッパリした形に表すこともできます.

...  ? (true_case) : (false_case)

またelseがない場合は

...  ... if 

というように短くできます.

case-when-end

caseは一つの式に対する一致判定を行います.when節で指定された値と最初の式を評価した結果とを演算子===を用いて比較し, 一致する場合にはwhen節の本体を評価します.

case []
[when  [, ] ...[, `*' 式] [then]
  式..]..
[when `*'  [then]
  ..]..
[else
  ..]
end

配列

Rubyでは配列を[ ]で表します.

Array.each

eachは配列の中の要素を順番に読み込み変数に代入する.

[ ... ].each do |変数|
  
end

うるう年かどうかの判定

うるう年の規則は,

  • 400で割り切れる数の年はうるう年
  • 400で割り切れず, 100で割り切れる数の年は平年
  • 上の条件を満たさない場合, 4で割り切れる数の年はうるう年, そうでなければ平年

この規則に従い, leap?関数を作り, 2000, 1900, 2004, 1999の4つの年のうるう年判定を行います.

以下にプログラムと実行結果を記します.

単純にif文を用いる

def leap?(year)
  if year % 400 == 0
    p true
  elsif year % 100 == 0
    p false
  elsif year % 4 == 0
    p true
  else
    p false
  end
end

[2000, 1900, 2004, 1999].each do |year|
  p year
  leap?(year)
end

少し長いため, case文を用いてスッキリさせます.

case文を用いる

def leap?(year)
  return case
     when year % 400 == 0 ; true
     when year % 100 == 0 ; false
     when year % 4 == 0   ; true
     else                 ; false
     end
end

[2000, 1900, 2004, 1999].each do |year|
  p year
  p leap?(year)
end

実行結果

> ruby check_leap_year.rb
2000
true
1900
false
2004
true
1999
false

無事完了.

参考資料

プログラミング言語 Ruby リファレンスマニュアル閏年 – Wikipedia

3
1
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
3
1