2012年9月12日水曜日

開発環境

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

その他参考書籍

バースデーヘルパー

コード(TextWrangler)

sample.rb

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

def get_age t
  birth = Time.gm(t.year)
  td = Time.new
  age = 0
  
  while birth.year < td.year
    age += 1
    birth = Time.gm(t.year + age)
  end
  
  age -= 1 if t.month == td.month and t.day > td.day
  age -= 1 if t.month > td.month
  age
end

birth_days = {}
File.read('birth_day_helper').each_line do |line|
  name,date,year = line.split(',')
  month,day = date.split
  birth_days[name] = Time.gm(year,month,day)
end

while true
  puts "名前を入力"
  name = gets.chomp
  break if name =~/^\s*$/
  if birth_days[name] == nil
    puts 'その人物の誕生日は分かりません'
  else
    puts "#{birth_days[name]} age:#{get_age birth_days[name]}"
  end  
end

入出力結果(Terminal)

$ cat birth_day_helper
Christopher Alexander,  Oct  4, 1936
Christopher Lambert,    Mar 29, 1957
Christopher Lee,        Sep 11, 1922
Christopher Lloyd,      Sep 12, 1922
Christopher Pine,       Sep 13, 1922
Christopher Plummer,    Apr 20, 2000
Christopher Walken,     Apr 21, 2000
The King of Spain,      Apr 22, 2000
$ ./sample.rb
名前を入力
Christopher Lee
1922-09-11 00:00:00 UTC age:90
名前を入力
Christopher Lloyd
1922-09-12 00:00:00 UTC age:90
名前を入力
Christopher Pine
1922-09-13 00:00:00 UTC age:89
名前を入力
kamimura
その人物の誕生日は分かりません
名前を入力

$

0 コメント:

コメントを投稿