開発環境
- OS X Lion - Apple(OS)
- BBEdit - Bare Bones Software, Inc.(Text Editor)
- プログラミング言語: Ruby
『初めてのプログラミング 第2版』(Chris Pine 著、長尾 高弘 訳、オライリー・ジャパン、2010年、ISBN978-4-87311-469-9)の 14章(ブロックとproc), 14.4(練習問題)おじいさんの時計 を解いてみる。
その他参考書籍
- 『プログラミング言語 Ruby』David Flanagan, まつもと ゆきひろ 著 、卜部 昌平 監訳、長尾 高弘 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-394-4)
- Rubyクックブック ―エキスパートのための応用レシピ集
おじいさんの時計
コード(BBEdit)
sample.rb
#!/usr/bin/env ruby2.0
#-*- coding: utf-8 -*-
def grandfather_clock &block
h = Time.new.hour
if h > 12
h -= 12
elsif h == 0
h = 12
end
h.times do
block.call
end
end
puts Time.new
grandfather_clock do
puts 'DONG'
end
入出力結果(Terminal)
$ ./sample.rb 2013-03-18 16:56:30 +0900 DONG DONG DONG DONG $
ちなみにJavaScriptの場合。
コード(BBEdit)
var grandfatherClock = function( fn ) {
var h = new Date().getHours(),
i;
if ( h > 12 ) {
h -= 12;
} else if ( h === 0 ) {
h = 12;
}
for ( i = 0; i < h; i += 1 ) {
fn();
}
},
$pre = $('#pre0');
$pre.html("");
$pre.append(new Date() + "\n");
grandfatherClock( function ( ) {
$('#pre0').append("DOG!\n");
});
pythonの場合。
sample.py
コード(BBEdit)
#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-
import time
def f(fun):
h = time.localtime().tm_hour
if h > 12:
h -= 12
elif h == 0:
h = 12
for x in range(h):
fun()
def g():
print("DONG!")
f(g)
入出力結果(Terminal)
$ ./sample.py DONG! DONG! DONG! DONG! DONG! $
0 コメント:
コメントを投稿