Ruby入門の練習解答例

練習:分岐の解答例_

上記のメソッド branch_testを以下の条件を満たすように書き直せ。

  • Good morningは6時から12時前までとする。
  • Good afternoonは 12時から18時前までとする。
  • Good eveningは 0時から6時前、また、18時から24時までとする。
  • 1日は24時間とする。
/Users/gotoh% irb
?> def branch_test(x)
?>   if 6 <= x && x < 12
?>     puts "Good morning."
?>   elsif 12 <= x && x < 18
?>     puts "Good afternoon."
?>   else
?>     puts "Good evening."
?>   end
>> end
=> :branch_test
>> branch_test(9)
Good morning.
=> nil                                                                          
>> branch_test(14)
Good afternoon.
=> nil                                                                          
>> branch_test(0)
Good evening.
=> nil                                                                          
>> 

練習:繰り返し処理_

先に作成したthree_times(value)を繰り返し処理を使って、many_times(num, str)に拡張せよ。なお、many_timesはstrをnum回表示するメソッドとする。

?> def many_times(num, str)
?>   num.times do | idx |
?>     puts str
?>   end
>> end
=> :many_times
>> many_times(5, "Hello World!")
Hello World!
Hello World!                                                 
Hello World!                                                 
Hello World!                                                 
Hello World!                                                 
=> 5             

正規表現の練習_

東京理科大の学籍番号を検出する正規表現を書き、matchメソッドを使って正しいかどうか確かめよ。 なお、正規表現の書き方については Ruby 3.0.0 リファレンスマニュアル:正規表現 を参照にせよ。

理科大の学籍番号は7桁の整数である。2021年度の履修者名簿を見ると全員1からスタートした学籍番号であったので、先頭を1とし、その後0から9までの数字が6個並んでいる文字列にマッチするようにした。

>> reg = /^1[0-9]{6}$/
=> /^1[0-9]{6}$/
>> reg.match("1119043")
=> #<MatchData "1119043">
>> reg.match("1417012")
=> #<MatchData "1417012">
>> reg.match("1418001")
=> #<MatchData "1418001">
>> reg.match("ABCDEFG")
=> nil
>> reg.match("12345678")
=> nil
>> reg.match("1234567")
=> #<MatchData "1234567">

戻る_