2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ruby 演習メモ III (if, case, array, each by leap year)

Last updated at Posted at 2020-12-31

目的

ruby のコードを実際に書いてみよう.
今回は第 III 弾.

お題

以下のような method leap? をつくれ.

  • 関数名 : leap?
  • 入力 : year (年)
  • 出力 : true or false (year がうるう年なら true)

(https://qiita.com/daddygongon/items/a550bde1ed6bff5217d8 にある課題)

今回書いた code


def leap?(year)
  return  (year%400 == 0) ? true :
	    (year%100 == 0) ? false :
	      (year%4 == 0) ? true : false
end

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

解説

実際には TDD を意識して code を書いたが, 作業手順については割愛する.
(先程のリンク先にある手順通りに作成したので, 気になるならそこを見に行ったら良い)

ここから code 自体の解説.

  • leap? の中身
    三項演算子で書いてる. 以下の code と同じことしてる.

    return case
       when year % 400 ==0 ; true
       when year % 100 ==0 ; false
       when year % 4 ==0   ; true
       else                ; false
       end
    
  • main loop の中身
    [1900,2004,1999].each do |year| - end は loop.
    配列 [1900,2004,1999] の各要素を順に取り出してる.
    取り出した要素は year に入ってる.

参考資料

チャート式ruby-III(if, case, Array.each by leap year)


  • source ~/Lecture/multiscale_simulation/grad_members_20f/members/gagagagazelle/docs/c3_if_case_leap_year.org
2
0
0

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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?