Learn Ruby

Tuesday, July 04, 2006

 

如何控制output的格式

最简单的是用 printf,格式使用起来跟C的语法一样
如下面的语句
testfile = File.new("testfile", "w")
a = 5
for i in 1..10 do
testfile.printf("%0#{a}d \n", i)
end

那么得到的结果就是
$cat testfile
00001
00002
00003
00004
00005
00006
00007
00008
00009
00010

注意设置宽度是用#{a}把变量a的值传递到字符串内

Comments: Post a Comment

Subscribe to Post Comments [Atom]





<< Home

Archives

July 2006   April 2007  

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]