p "0123456789".centered(3) # "456"
p "012".centered(5) # " 012 "
p "012".centered(4) # "012 "
p "012".centered(3) # "012"
p "012".centered(2) # "12"
p "012".centered(1) # "1"
p "012".centered(0) # ""
p "012".centered(-1) # "012"
p "012".center(4) == " 012 ".centered(4) # true
1
2
3
4
5
6
7
8
9
10
11
--- center.rb.orig 2007-11-19 17:17:47.000000000 +0900+++ center.rb 2007-11-19 17:17:39.000000000 +0900@@ -1,7 +1,7 @@
class String
def centered(width = 80)
- return center(width) if width > size- self[(size - width) / 2, width]+ return center(width) if width > size or 0 > width+ self[-((width - size) / 2), width]
end
end
ihag
#4242()
[
diff
]
Rating0/0=0.00
String#centerは右側からパディングを入れるようですので,それにあわせて,widthをはみ出す場合は「左側から削る」ようにしました.
Rubyでは,(CやPerlと異なり)負の整数の除算の場合,剰余の符号が除数(divisor)の符号と一致するような商が得られますが,4行目で文字列を削る際にその性質を利用しています. (4171 を見てぱくりました.勉強になります:-)
Rating0/0=0.00-0+