開発環境
- OS X Lion - Apple(OS)
- BBEdit - Bare Bones Software, Inc.(Text Editor)
- Script言語:Ruby
『初めてのプログラミング 第2版』(Chris Pine 著、長尾 高弘 訳、オライリー・ジャパン、2010年、ISBN978-4-87311-469-9)の 6章(メソッドの詳細), 6.2(練習問題)目次 を解いてみる。
その他参考書籍
- 『プログラミング言語 Ruby』David Flanagan, まつもと ゆきひろ 著 、卜部 昌平 監訳、長尾 高弘 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-394-4)
- Rubyクックブック ―エキスパートのための応用レシピ集
目次
コード(BBEdit)
sample.rb
#!/usr/bin/env ruby1.9 #-*- coding: utf-8 -*- width = 40 puts "table of contents".center(width) puts puts "chapter 1: start".ljust(width / 2) + "p.1".rjust(width / 2) puts "chapter 2: number".ljust(width / 2) + "p.11".rjust(width / 2) puts "chapter 3: string".ljust(width / 2) + "p.15".rjust(width / 2)
入出力結果(Terminal)
$ ./sample.rb
table of contents
chapter 1: start p.1
chapter 2: number p.11
chapter 3: string p.15
$
ちなみにJavaScriptの場合。
コード(BBEdit)
String.prototype.center = function(n){
var result = "";
for(var i = 0; i < (n - this.length) / 2; i++){
result += " ";
}
result += this;
return result;
};
String.prototype.ljust = function(n){
var result = this;
for(var i = 0; i < n - this.length; i++){
result += " ";
}
return result;
};
String.prototype.rjust = function(n){
var result = "";
for(var i = 0; i < n - this.length; i++){
result += " ";
}
result += this;
return result;
};
var width = 40;
var result = "table of contents".center(width) + "\n" +
"\n" +
"chapter 1: start".ljust(width / 2) + "p.1".rjust(width / 2) + "\n" +
"chapter 2: number".ljust(width / 2) + "p.11".rjust(width / 2) + "\n" +
"chapter 3: string".ljust(width / 2) + "p.15".rjust(width / 2) + "\n";
$('#pre0').text(result);
pythonの場合。
sample.py
コード(BBEdit)
#!//usr//bin//env python3.3
# -*- coding: utf-8 -*-
width = 40
print("table of contents".center(width))
print()
print("chapter 1: start".ljust(width // 2) + "p.1".rjust(width // 2))
print("chapter 2: number".ljust(width // 2) + "p.11".rjust(width // 2))
print("chapter 3: string".ljust(width // 2) + "p.15".rjust(width // 2))
入出力結果(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 $width = 40;
my $half = $width / 2;
my $s = "table of contents";
print " " x (($width - length $s) / 2) . $s . "\n\n";
printf "%-${half}s %${half}s\n", "chapter 1: start", "p.1";
printf "%-${half}s %${half}s\n", "chapter 2: number", "p.11";
printf "%-${half}s %${half}s\n", "chapter 3: string", "p.15";
入出力結果(Terminal)
$ ./sample.pl
table of contents
chapter 1: start p.1
chapter 2: number p.11
chapter 3: string p.15
$
0 コメント:
コメントを投稿