開発環境
- OS X Lion - Apple(OS)
- Emacs、BBEdit - Bare Bones Software, Inc. (Text Editor)
- Ruby (プログラミング言語)
『初めてのプログラミング 第2版』(Chris Pine 著、長尾 高弘 訳、オライリー・ジャパン、2010年、ISBN978-4-87311-469-9)の 12章(新しいクラスのオブジェクト), 12.6(練習問題の続き)、バースデーヘルパー、を解いてみる。
その他参考書籍
- 『プログラミング言語 Ruby』David Flanagan, まつもと ゆきひろ 著 、卜部 昌平 監訳、長尾 高弘 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-394-4)
- Rubyクックブック ―エキスパートのための応用レシピ集
バースデーヘルパー!
コード(BBEdit)
sample.rb
#!/usr/bin/env ruby2.0
#-*- coding: utf-8 -*-
filename = 'birth_day_helper.txt'
birth_dates = {}
read_string = File.read filename
read_string.each_line do |line|
line = line.chomp
name, mon_day, year = line.split ","
mon, day = mon_day.split
birth_dates[name] = Time.gm(year, mon, day)
end
td = Time.new
td_year = td.year
td_mon = td.mon
td_day = td.day
while true
print '名前を入力: '
name = gets.chomp
break if name =~ /^\s*$/
next if birth_dates[name] == nil
birth_date = birth_dates[name]
birth_year = birth_date.year
birth_mon = birth_date.mon
birth_day = birth_date.day
age = td_year - birth_date.year
if td_mon < birth_mon or (td_mon == td_mon and td_day < birth_day)
age -= 1
end
puts "birth day:#{birth_date} age:#{age}"
end
入出力結果(Terminal)
$ ./sample.rb 名前を入力: Christopher Pine birth day:2000-10-21 00:00:00 UTC age:13 名前を入力: Christopher Plummer birth day:2000-10-22 00:00:00 UTC age:13 名前を入力: Christopher Lloyd birth day:2000-10-23 00:00:00 UTC age:12 名前を入力: ruby 名前を入力: $ cat birth_day_helper.txt Christopher Alexander, Oct 18, 1936 Christopher Lambert, Mar 12, 2000 Christopher Lee, Mar 13, 2000 Christopher Pine, Oct 21, 2000 Christopher Plummer, Oct 22, 2000 Christopher Lloyd, Oct 23, 2000 The King of Spain, Feb 6, 2000 $
ちなみにpython3.4の場合。
コード(BBEdit)
sample.py
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import datetime
import re
months = {'Jan': 1,
'Feb': 2,
'Mar': 3,
'Apr': 4,
'May': 5,
'Jun': 6,
'Jul': 7,
'Aug': 8,
'Sep': 9,
'Oct': 10,
'Nov': 11,
'Dec': 12}
filename = 'birth_day_helper.txt'
birth_dates = {}
with open(filename) as f:
for line in f:
name, month_day, year = line.split(',')
month, day = month_day.strip().split()
birth_dates[name] = datetime.date(int(year), months[month], int(day))
td = datetime.date.today()
year = td.year
month = td.month
day = td.day
while True:
name = input('名前を入力: ')
if re.search(r'^\s*$', name):
break
if not name in birth_dates:
print("一覧に名前がありません。")
else:
birth_date = birth_dates[name]
birth_year = birth_date.year
birth_month = birth_date.month
birth_day = birth_date.day
age = year - birth_year
if birth_month > month or (birth_month == month and birth_day > day):
age -= 1
print('誕生日: {0}年{1}月{2}日 年齢: {3}歳'.format(
birth_year, birth_month, birth_day, age))
入出力結果(Terminal)
$ ./sample.py 名前を入力: Christopher Pine 誕生日: 2000年10月21日 年齢: 13歳 名前を入力: Christopher Plummer 誕生日: 2000年10月22日 年齢: 13歳 名前を入力: Christopher Lloyd 誕生日: 2000年10月23日 年齢: 12歳 名前を入力: python 一覧に名前がありません。 名前を入力: $
0 コメント:
コメントを投稿