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 number 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:(As you can see from the other answers, there are plenty of ways of coding the loop itself.)
Here
iis always a number, but the expression"%02d" % iformatsias a two-digit number, just for display purposes.