開発環境
- OS X Lion - Apple(OS)
- TextWrangler(Text Editor) (BBEditの機能制限無料版、light版)
- Script言語:Ruby
『初めてのプログラミング 第2版』(Chris Pine 著、長尾 高弘 訳、オライリー・ジャパン、2010年、ISBN978-4-87311-469-9)の 2章(数値), 2.5(練習問題)秒で数えた年齢 を解いてみる。
その他参考書籍
- 『プログラミング言語 Ruby』David Flanagan, まつもと ゆきひろ 著 、卜部 昌平 監訳、長尾 高弘 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-394-4)
- Rubyクックブック ―エキスパートのための応用レシピ集
秒で数えた年齢
コード(TextWrangler)
sample.rb
#!/usr/bin/env ruby1.9 # -*- coding: utf-8 -*- td = Time.new birth = Time.local(2000, 1, 2, 3, 4, 5) puts "誕生日: #{birth}" puts "今日: #{td}" puts "経過秒数: #{(Time.new - birth).to_i}秒"
入出力結果(Terminal)
$ ./sample.rb 誕生日: 2000-01-02 03:04:05 +0900 今日: 2012-12-03 16:50:28 +0900 経過秒数: 407771183秒 $
ちなみにJavaScriptの場合。
コード(TextWrangler)
var result = ""; var td = new Date(); var birth = new Date(2000, 1 - 1, 2, 3, 4, 5); result += "誕生日: " + birth + "\n" + "今日: " + td + "\n" + "経過秒数: " + Math.round((td - birth) / 1000) + "秒\n"; $('#pre0').text(result);
pythonの場合。
sample.py
コード(TextWrangler)
#!/usr/bin/env python3.3 # -*- coding: utf-8 -*- import datetime td = datetime.datetime.today() ago = datetime.datetime(2000, 1, 2, 3, 4, 5) print("誕生日: {0}".format(ago)) print("今日: {0}".format(td)) print("経過秒数: {0}秒".format(int(td.timestamp() - ago.timestamp())))
入出力結果(Terminal)
$ ./sample.py 誕生日: 2000-01-02 03:04:05 今日: 2012-12-03 16:57:31.848162 経過秒数: 407771606秒 $
perlの場合。
sample.pl
コード(TextWrangler)
#!/usr/bin/env perl use strict; use warnings; use utf8; use 5.016; binmode STDIN, ':utf8'; binmode STDOUT, ':utf8'; use Time::Local; my @birth = (2000, 1, 2, 3, 4, 5); my($sec, $min, $hour, $mday, $mon, $year) = localtime; my $td = timelocal((localtime)[0..5]); my $birth = timelocal($birth[5], $birth[4], $birth[3], $birth[2], $birth[1] - 1, $birth[0] - 1900); printf "誕生日: %d-%02d-%02d %02d:%02d:%02d\n", @birth; printf "今日: %d-%02d-%02d %02d:%02d:%02d\n", $year + 1900, $mon + 1, $mday, $hour, $min, $sec; print "経過病数: " . ($td - $birth) . "秒\n";
入出力結果(Terminal)
$ ./sample.pl 誕生日: 2000-01-02 03:04:05 今日: 2012-12-03 17:02:31 経過病数: 407771906秒 $
0 コメント:
コメントを投稿