LoginSignup
10
0

More than 3 years have passed since last update.

Rubyのお勉強<制御構造_Ifとか>

Last updated at Posted at 2020-11-18

Document Links

bundler

Rubyの制御構造に入る前に...

講義資料にもあるがbundlerがなんとかかんとか...

説明できるほどはわからないので,詳しくは講義資料を見てください.

if-elsif-else-end

Rubyリファレンスマニュアルでif文の文法は,

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

と記述されている.

閏年判定(単年)

もし閏年なら"true"を返すようにするには,

p year = ARGV[0].to_i

if year % 4 == 0
  p true
end

実行結果

$ ruby check_leap.rb 2004
2004
true

では,閏年以外なら"false"を返すようにするなら,

p year = ARGV[0].to_i
if year%4 == 0
  p true
else
  p false
end

実行結果

$ ruby check_leap.rb 1999
1999
false

閏年の条件は4年に一度だけじゃないみたい,

  • 西暦年号が4で割り切れる年をうるう年とする.
  • 西暦年号が100で割り切れて400で割り切れない年は平年とする.

では,その条件も含めると,

p year = ARGV[0].to_i
if year%400 == 0
  p true
elsif year%100 == 0
  p false
elsif year%4 == 0
  p true
else
  p false
end

実行結果

$ ruby check_leap.rb 1900
1900
false
$ ruby check_leap.rb 2000
2000
true

閏年判定(複数年)

複数年を判定するときに何度も打つのが面倒なら,配列にしてloop回すだけ.

[2004,1999,1900,2000].each do |year|
  p year
  if year%400 == 0
    p true
  elsif year%100 == 0
    p false
  elsif year % 4 == 0
    p true
  else
    p false
  end
end

実行結果

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

判定部分をmethodにしますか,

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

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

*コメントで指摘していただいたので修正する.

講義資料にも書かれていたが,

  • true falseを返して,main loopでpする方がいいです.

とのこと,なので,

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

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

詳しくはコメント欄で,非常に丁寧な解説をしていただいています.

case

Rubyリファレンスマニュアルのif文の下の方に,caseについて載っている.

caseを使って,より美しくするなら,

check_leap_year_case.rb
def leap?(year)
  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

てな感じにもできるみたい.

締め

今回は条件処理について学んだ.

次回,Rakeで自動化&Export


  • source ~/school/multi/my_ruby/grad_members_20f/members/evendemiaire/post/if_case.org
10
0
2

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