LoginSignup
4
1

More than 3 years have passed since last update.

Rubyのif,case

Posted at

!Mac OS X-10.15.7 !ruby-2.7.1p83

if-elsif-else-end

if文の書き方

if 条件式 then
  処理
elsif 条件式 then
  処理 
else
  処理 
end

閏年判定(単数)

まず4の倍数なのかを判定する

p year = ARGV[0].to_i

if year%4==0 then
  p true
else
  p false
end

yearを入力として、それは4の倍数ならtrue、そうじゃなければfalse  実行すると

$ ruby check_leap.rb 2004
2004
true

では、1999でやってみる

$ ruby check_leap.rb 1999
1999
false

となる
閏年の条件は4年に一度だけじゃなく
1)100で割り切れる年はうるう年でなく
2)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にしておく

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

case

case文の書き方

case A
when 1 then  
  処理
when 2 then  
  処理
else       
  処理
end

caseを使って先ほどのコードを書きなおして

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

プログラムは短くなった


  • source ~/grad_members_20f/members/wjswnsrud12/memo7.org
4
1
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
4
1