2012年10月19日金曜日

開発環境

『初めてのプログラミング 第2版』(Chris Pine 著、長尾 高弘 訳、オライリー・ジャパン、2010年、ISBN978-4-87311-469-9)の 12章(新しいクラスのオブジェクト), 12.6(練習問題の続き)バースデーヘルパー を解いてみる。

その他参考書籍

バースデーヘルパー

コード(TextWrangler)

sample.rb

#!/usr/bin/env ruby1.9
#-*- coding: utf-8 -*-

file = open('birth_day_helper')
birth = {}
file.each_line do |line|
  line.chomp
  name, day_and_month, year = line.split(',')
  month, day = day_and_month.split
  birth[name] = Time.gm(year, month, day)
end

td = Time.new
while true
  print "名前を入力: "
  name = gets.chomp
  break if name =~ /^\s*$/
  unless birth[name]
    puts "その名前の誕生日は載っていません。"
    next
  end
  birth_day = birth[name]
  age = td.year - birth_day.year
  age -= 1 if td.month < birth_day.month or (td.month == birth_day.month and td.day < birth_day.day)
  puts "誕生日: #{birth_day.year}年#{birth_day.month}月#{birth_day.day}日 年齢: #{age}"
end

入出力結果(Terminal)

$ ./sample.rb
名前を入力: ruby
その名前の誕生日は載っていません。
名前を入力: Christopher Lee
誕生日: 1950年10月18日 年齢: 62
名前を入力: Christopher Lloyd
誕生日: 1950年10月19日 年齢: 62
名前を入力: Christopher Pine
誕生日: 1950年10月20日 年齢: 61
名前を入力: Christopher Plummer
誕生日: 2000年4月20日 年齢: 12
名前を入力: 
$

0 コメント:

コメントを投稿