開発環境
- OS X Lion - Apple(OS)
- TextWrangler(Text Editor) (BBEditの機能制限無料版、light版)
- Script言語:Ruby
『初めてのプログラミング 第2版』(Chris Pine 著、長尾 高弘 訳、オライリー・ジャパン、2010年、ISBN978-4-87311-469-9)の 12章(新しいクラスのオブジェクト), 12.6(練習問題の続き)バースデーヘルパーを解いてみる。
その他参考書籍
- 『プログラミング言語 Ruby』David Flanagan, まつもと ゆきひろ 著 、卜部 昌平 監訳、長尾 高弘 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-394-4)
バースデーヘルパー
コード(TextWrangler)
#!/usr/bin/env ruby #encoding: utf-8 filename = 'birth_day_helper' name_birth = {} File.read(filename).each_line do |line| name, date, year = line.split(',') month, day = date.split() name_birth[name] = Time.gm(year,month,day) end while true puts '誕生日を知りたい人物の名前を入力(空文字で終了)' name = gets.chomp break if name =~ /^\s*$/ birth = name_birth[name] if birth td = Time.new bday = birth.day bmonth = birth.month byear = birth.year age = 1 while Time.gm(byear + age, bmonth, bday) <= td age += 1 end puts "誕生年月日: #{birth} 年齢:#{age - 1}歳" else puts 'その人物の誕生日は分かりません。' end end
入出力結果(Terminal)
$ cat birth_day_helper Christopher Alexander, Oct 4, 1936 Christopher Lambert, Mar 29, 1957 Christopher Lee, May 27, 1922 Christopher Lloyd, Dec 15, 1938 Christopher Pine, Dec 16, 1938 Christopher Plummer, Mar 21, 2000 Christopher Walken, Mar 22, 2000 The King of Spain, Mar 23, 2000 $ ./ruby_program.rb 誕生日を知りたい人物の名前を入力(空文字で終了) Christopher Alexander 誕生年月日: Sun Oct 04 00:00:00 UTC 1936 年齢:75歳 誕生日を知りたい人物の名前を入力(空文字で終了) Christopher Plummer 誕生年月日: Tue Mar 21 00:00:00 UTC 2000 年齢:12歳 誕生日を知りたい人物の名前を入力(空文字で終了) Christopher Walken 誕生年月日: Wed Mar 22 00:00:00 UTC 2000 年齢:12歳 誕生日を知りたい人物の名前を入力(空文字で終了) The King of Spain 誕生年月日: Thu Mar 23 00:00:00 UTC 2000 年齢:11歳 誕生日を知りたい人物の名前を入力(空文字で終了) kamimura その人物の誕生日は分かりません。 誕生日を知りたい人物の名前を入力(空文字で終了) $
今回の周ではirb(インタラクティブRuby)も少しずつ活用してみることに。
本書を続けつつ、上記の本を入手したらそっちに切り替え。
0 コメント:
コメントを投稿