文字列のセンタリング
Posted feedbacks - Ruby
これまたけれんみのない、#4120と同様の実装。rubyらしくStringを拡張して格調高く。
Dan the Occasional Rubyist
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class String
def centered(width)
width ||= 80
margin = (width - self.length)/2;
return self if margin == 0
return " " * margin + self if margin > 0
self[-margin..margin-1]
end
end
ARGF.readlines.each{|l| puts l.centered(72) }
__END__
0 1 2 3 4 5 6 7
012345678901234567890123456789012345678901234567890123456789012345678901
This line is intentionally longer than 72 chars to test String#centered works fine.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | def centering(lst,n)
return lst if (n <= 0 || lst == "")
c = (lst = " "*n + lst + " "*n).size/2
lst[c-n/2..-1][0..n-1]
end
if __FILE__ == $0
p (s = centering("end",4)) != " end" ? s : :ok
p (s = centering("end",3)) != "end" ? s : :ok
p (s = centering("end",2)) != "en" ? s : :ok
p (s = centering("end",1)) != "n" ? s : :ok
p (s = centering("end",0)) != "end" ? s : :ok
p (s = centering("end",-1)) != "end" ? s : :ok
p (s = centering("",0)) != "" ? s : :ok
p (s = centering("",1)) != "" ? s : :ok
end
|
String#centerを使って少し修正しました.
また,入力行がちょうどwidth文字 + \nのときに,頭の一文字と\nを切り落としてしまっていたので,centeredに渡す前にchompするようにしました.
また,入力行がちょうどwidth文字 + \nのときに,頭の一文字と\nを切り落としてしまっていたので,centeredに渡す前にchompするようにしました.
1 2 3 4 5 6 7 8 9 10 11 12 13 | class String
def centered(width = 80)
margin = (width - self.length)/2;
return center(width) if margin >= 0
self[-margin..margin-1]
end
end
ARGF.readlines.each{|l| puts l.chomp.centered(72) }
__END__
0 1 2 3 4 5 6 7
012345678901234567890123456789012345678901234567890123456789012345678901
This line is intentionally longer than 72 chars to test String#centered works fine.
|
Stringを拡張。 削るときは後ろを優先。
1 2 3 4 5 6 7 8 9 10 | class String
def neko_center (w)
if (d = self.size - w) > 0
#self.gsub(/\A.{#{d/2}}|.{#{(d+1)/2}}\Z/, '')
self[d/2..-d/2-1]
else
self.center(w)
end
end
end
|
さらに修正しました. #4173 で,ご指摘を受けた不具合も直っています.
p "0123456789".centered(3) # "345"
p "012".centered(5) # " 012 "
p "012".centered(4) # "012 "
p "012".centered(3) # "012"
p "012".centered(2) # "01"
p "012".centered(1) # "1"
p "012".centered(0) # ""
1 2 3 4 5 6 7 8 9 10 11 12 | class String
def centered(width = 80)
return center(width) if width > size
self[(size - width) / 2, width]
end
end
ARGF.readlines.each{|l| puts l.chomp.centered(72) }
__END__
0 1 2 3 4 5 6 7
012345678901234567890123456789012345678901234567890123456789012345678901
This line is intentionally longer than 72 chars to test String#centered works fine.
|





nobsun
#4089()
Rating0/2=0.00
文字列を指定のカラム幅にセンタリング配置する関数を示してください。文字列の長さが指定した幅より長い場合には文字列の両端をできるだけ均等に切り落して指定幅に収めてください。1文字は1カラムに収まるものと仮定してかまいません。
[ reply ]