開発環境
- OS X Lion - Apple(OS)
- TextWrangler(Text Editor) (BBEditの機能制限無料版、light版)
- Script言語:Ruby
『初めてのプログラミング 第2版』(Chris Pine 著、長尾 高弘 訳、オライリー・ジャパン、2010年、ISBN978-4-87311-469-9)の 14章(ブロックとproc), 14.4(練習問題の続き)おじいさんの時計 を解いてみる。
その他参考書籍
- 『プログラミング言語 Ruby』David Flanagan, まつもと ゆきひろ 著 、卜部 昌平 監訳、長尾 高弘 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-394-4)
- Rubyクックブック ―エキスパートのための応用レシピ集
おじいさんの時計
コード(TextWrangler)
sample.rb
#!/usr/bin/env ruby1.9 # -*- coding: utf-8 -*- def grandfather_clock &block h = Time.new.hour h = 12 if h == 0 h -= 12 if h > 13 h.times do block.call end end puts Time.new grandfather_clock do puts 'DONG!' end
入出力結果(Terminal)
$ ./sample.rb 2012-11-28 16:06:23 +0900 DONG! DONG! DONG! DONG! $
ちなみにJavaScriptの場合。
コード(TextWrangler)
function grandfather_clock(f){ var h = (new Date()).getHours(); h = h === 0 ? 12: h > 12 ? (h - 12) : h; for(var i = 0; i < h; i++){ f(); } } $('#pre0').append((new Date()) + "\n"); grandfather_clock(function (){ $('#pre0').append("DONG!\n"); });
pythonの場合。
sample.py
コード(TextWrangler)
#!/usr/bin/env python3.3 # -*- coding: utf-8 -*- def grandfather_clock(f): import time h = time.localtime().tm_hour if h == 0: h = 12 if h > 12: h -= 12 for x in range(h): f() def f(): print("DONG!"); import time print(time.localtime()) grandfather_clock(f);
入出力結果(Terminal)
$ ./sample.py time.struct_time(tm_year=2012, tm_mon=11, tm_mday=28, tm_hour=16, tm_min=25, tm_sec=23, tm_wday=2, tm_yday=333, tm_isdst=0) DONG! DONG! DONG! DONG! $
0 コメント:
コメントを投稿