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

第七回講義メモ

Last updated at Posted at 2020-12-31

!Mac OS X-10.15.7 !ruby-2.6.3p62

条件分岐, Array

例題1

条件分岐を勉強していく上で, うるう年を例にあげる.

入力がうるう年(leap year)かどうかを表示するプログラムをかけ.
1. うるう年は4で割り切れる数の年.ただし,
2. 100で割り切れる年はうるう年でなく,
3. 400で割り切れる年はうるう年.
4. 2004, 1999, 1900, 2000で試せ.
5. それぞれtrue, false, false, true

一番簡単な条件分岐

rubyではif, elsif, else, endを使う.(以下例)

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

*例題2引数として年を受け取り, 閏年か否かを判定するコードを書け.

実装

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

結果(2000, 1999)

> ruby check_leap_2004.rb 2000
2000
true

> ruby check_leap_2004.rb 1999
1999
false

テストの自動化

テスト内容が増えた際はテストを自動化させたいし, その方が効率が良い.具体的には配列にして, loopで回すだけ.

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

case

caseを使って, より短いコードで実装を目指す.caseの動きは以下を参考.(https://docs.ruby-lang.org/ja/2.5.0/doc/spec=2fcontrol.html#if)

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

これを用いると以下のように書くことができる.

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

参考サイト

https://qiita.com/daddygongon/items/a550bde1ed6bff5217d8


  • source ~/my_ruby/grad_members_20f/members/drop-sd/lectures/no7.org
1
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
1
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?