2012年11月28日水曜日

開発環境

『初めてのプログラミング 第2版』(Chris Pine 著、長尾 高弘 訳、オライリー・ジャパン、2010年、ISBN978-4-87311-469-9)の 14章(ブロックとproc), 14.4(練習問題の続き)おじいさんの時計 を解いてみる。

その他参考書籍

おじいさんの時計

コード(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 コメント:

コメントを投稿