7
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.

第7回

Last updated at Posted at 2020-12-09

if-elsif-else-end 

お題

うるう年かどうかを判定するcodeを書け.

1. うるう年は4で割り切れる数の年.ただし,100で割り切れる年はうるう年でなく,400で割り切れる年はうるう年.
2. 2004, 1999, 1900, 2000で試せ.それぞれtrue, false, false, trueとなる.

簡単な解説

Rubyリファレンスマニュアルの「使用version」/「「Rubyの文法:制御構造」/「条件分岐if」/「文法」に次のような記述がある.

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

ここで,thenは省略可能で,ifをつなげるのはelsifである.

caseで綺麗に書く.

先程のRubyリファレンスマニュアルの「条件分岐if」の下側にcaseの説明がある.

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

解説(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
[2004, 1999, 1900, 2000].each do |year|
  p year
  p leap?(year)
end

実行結果

$ ruby leap_year.rb
2004
true
1999
false
1900
false
2000
true

  • source ~/grad_members_20f/members/Kazufumi0823/a4.org
7
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
7
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?