Simon
Simon

Reputation: 629

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 number have the leading 0. I ran out of idea, so I'd appreciate a little help !

Upvotes: 2

Views: 1508

Answers (3)

Beanish
Beanish

Reputation: 1662

10.times do |x|
  puts "%02d" % x
end

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500175

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.

Upvotes: 9

coreyward
coreyward

Reputation: 80041

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 }

Upvotes: 6

Related Questions