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