2012年5月23日水曜日

開発環境

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

その他参考書籍

バースデーヘルパー

コード(TextWrangler)

#!/usr/bin/env ruby
#encoding: utf-8

birth_day_helper = {}
File.open('birth_day_helper').each_line do |line|
  line = line.chomp
  (name,month_day,year) = line.split(",")
  month,day = month_day.split
  birth_day_helper[name] = Time.gm(year.to_i,month,day.to_i)
end

while true
  print "名前を入力: "
  name = gets.chomp
  break if name =~ /^\s*$/
  birth = birth_day_helper[name]
  year, month, day = birth.year,birth.month,birth.day
  td = Time.new
  age = 0
  year += 1
  while Time.gm(year,month,day) <= td
    age += 1
    year += 1
  end
  puts "誕生年月日: #{birth} 年齢: #{age}歳"
end

入出力結果(Terminal)

$ cat birth_day_helper
Christopher Alexander,  Oct  4, 1936
Christopher Lambert,    Mar 29, 1957
Christopher Lee,        May 22, 1922
Christopher Lloyd,      May 23, 1922
Christopher Pine,       May 24, 1922
Christopher Plummer,    Apr 20, 2000
Christopher Walken,     Apr 21, 2000
The King of Spain,      Apr 22, 2000
$ ruby sample.rb
名前を入力: Christopher Lee
誕生年月日: Mon May 22 00:00:00 UTC 1922 年齢: 90歳
名前を入力: Christopher Lloyd
誕生年月日: Tue May 23 00:00:00 UTC 1922 年齢: 90歳
名前を入力: Christopher Pine
誕生年月日: Wed May 24 00:00:00 UTC 1922 年齢: 89歳
名前を入力: 
$

今日の収穫:

Timeクラスから年、月、日を取得するにはそれぞれyear、month、dayを使えばいいことを知る。

今回の周ではirb(インタラクティブRuby)も少しずつ活用してみることに。

まだ上記の本を入手してないのでまた最初から。

本書を続けつつ、上記の本を早く入手してそっちに切り替え。本書も飽きてきたから早く入手しないと。。

Learning Rubyを入手したので今周が終わったら切り替え。

0 コメント:

コメントを投稿