Leading zero and increment in ruby
I was looking on how to have a leading zero in ruby, and I found out the solution: use %02d" Now, I'd like to do a loop, and keep this zero ! When I do something like this
i = "%02d" % "1".to_i
until (i == 10)
puts i
i += 1
end
I have an error "Cannot convert FixNum to string". So I decide to do this
i = "%02d" % "1".to_i
"01"
until (i == 10)
puts i
i = i.to_i
i += 1
end
So, this time, the loop work, but only the first numbe开发者_StackOverflowr have the leading 0. I ran out of idea, so I'd appreciate a little help !
I'm not a Ruby developer, but fundamentally I think you need to separate out the idea of the number i
, and the text representation with a leading 0. So something like:
for i in (1..10)
puts "%02d" % i
end
(As you can see from the other answers, there are plenty of ways of coding the loop itself.)
Here i
is always a number, but the expression "%02d" % i
formats i
as a two-digit number, just for display purposes.
Don't convert to a string for output until you're ready to actually output. You don't increment string values, typically.
0.upto(10) { |i| puts "%02d" % i }
10.times do |x|
puts "%02d" % x
end
精彩评论