開発環境
- OS X Lion - Apple(OS)
- BBEdit - Bare Bones Software, Inc.(Text Editor)
- プログラミング言語: Ruby
『初めてのプログラミング 第2版』(Chris Pine 著、長尾 高弘 訳、オライリー・ジャパン、2010年、ISBN978-4-87311-469-9)の 8章(配列とイテレータ), 8.3(練習問題)目次改訂版 を解いてみる。
その他参考書籍
- 『プログラミング言語 Ruby』David Flanagan, まつもと ゆきひろ 著 、卜部 昌平 監訳、長尾 高弘 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-394-4)
- Rubyクックブック ―エキスパートのための応用レシピ集
目次改訂版
コード(BBEdit)
sample.rb
#!/usr/bin/env ruby1.9
#-*- coding: utf-8 -*-
contents = [['start','p.1'],['number','p.11'],['string','p.15']]
width = 40
h = width / 2
puts "table of contents".center(width)
puts
i = 1
contents.each do |content|
puts ('chapter ' + i.to_s + ':' + content[0]).ljust(h) + content[1].rjust(h)
i += 1
end
入出力結果(Terminal)
$ ./sample.rb
table of contents
chapter 1:start p.1
chapter 2:number p.11
chapter 3:string p.15
$
ちなみにJavaScriptの場合。
コード(BBEdit)
var contents = [['start','p.1'],['number','p.11'],['string','p.15']],
width = 40,
h = width / 2,
result = "",
s, i, max;
s = "table of contents";
result += new Array(Math.floor((width - s.length) / 2) + 1).join(" ") + s + "\n\n";
for (i = 0, max = contents.length; i < max; i += 1) {
s = "chapter " + (i + 1) + ":" + contents[i][0];
result += s + new Array(h - s.length + 1).join(" ");
s = contents[i][1];
result += new Array(h - s.length + 1).join(" ") + s + "\n";
}
$('#pre0').text(result);
pythonの場合。
sample.py
コード(BBEdit)
#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-
contents = [['start','p.1'],['number','p.11'],['string','p.15']]
width = 40
h = width // 2
print("table of contents\n".center(width))
i = 1
for content in contents:
print(('chapter ' + str(i) + ':' + content[0]).ljust(h) + content[1].rjust(h))
i += 1
入出力結果(Terminal)
$ ./sample.py
table of contents
chapter 1:start p.1
chapter 2:number p.11
chapter 3:string p.15
$
perlの場合。
sample.pl
コード(BBEdit)
#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
use 5.016;
binmode STDIN, ":utf8";
binmode STDOUT, ":utf8";
my @contents = (['start','p.1'],['number','p.11'],['string','p.15']);
my $width = 40;
my $h = $width / 2;
my $s = "table of contents";
print " " x ((length $s) / 2) . "$s\n\n";
my $ i = 1;
for (@contents) {
printf "%-${h}s%${h}s\n", "chapter $i: $_->[0]", $_->[1];
$i += 1;
}
入出力結果(Terminal)
$ ./sample.pl
table of contents
chapter 1: start p.1
chapter 2: number p.11
chapter 3: string p.15
$
0 コメント:
コメントを投稿