numbers output formatting

V

Vladimir Agafonkin

Hi.

How can I pad a number with "0"-s to a speciefied length when it goes
to the output? It's a very simple newbie question, yet I haven't been
able to find an answer in Programming Ruby book and core library docs.

Say, we have a following code:

for i in 1..10 do
puts "num #{i}"
end

What I need to change in this little script to format the output so
that it looks like this?

num 01
num 02
....
num 10

Thanks in advance.
 
R

Robert Klemme

Vladimir said:
Hi.

How can I pad a number with "0"-s to a speciefied length when it goes
to the output? It's a very simple newbie question, yet I haven't been
able to find an answer in Programming Ruby book and core library docs.

Say, we have a following code:

for i in 1..10 do
puts "num #{i}"
end

What I need to change in this little script to format the output so
that it looks like this?

num 01
num 02
...
num 10

Thanks in advance.

http://www.ruby-doc.org/core/classes/Kernel.html#M002972

robert
 
G

greg.rb

just one way to do it:

for i in 1..10 do
printf("%02d \n", i)
end

c documentation has more on printf
 
G

greg.rb

greg.rb said:
just one way to do it:

for i in 1..10 do
printf("%02d \n", i)
end

c documentation has more on printf
i forgot to put in 'num':

for i in 1..10 do
printf("num %02d \n", i)
end

produces:
num 01
num 02
num 03
num 04
num 05
num 06
num 07
num 08
num 09
num 10
 
S

Si

Vladimir said:
Hi.

How can I pad a number with "0"-s to a speciefied length when it goes
to the output? It's a very simple newbie question, yet I haven't been
able to find an answer in Programming Ruby book and core library docs.

Say, we have a following code:

for i in 1..10 do
puts "num #{i}"
end

What I need to change in this little script to format the output so
that it looks like this?

num 01
num 02
...
num 10

Thanks in advance.

also:

(1..10).each do |i|
puts "num #{'%02d' % i}"
end
 
K

Karl von Laudermann

Bah, printf() is for wimps.

for i in 1..10 do
puts "num " + ("0" * (1 - Math.log10(i).truncate)) + i.to_s
end

Just increase the 1 to increase the number of zeros. :)
 
D

Dumaiu

Karl said:
Bah, printf() is for wimps.

for i in 1..10 do
puts "num " + ("0" * (1 - Math.log10(i).truncate)) + i.to_s
end

Just increase the 1 to increase the number of zeros. :)

Better make sure he knows that was a joke!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,186
Messages
2,570,998
Members
47,587
Latest member
JohnetteTa

Latest Threads

Top