[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

[noob question] convert 7 in 07

Paul A.

4/22/2009 10:39:00 AM

Hi,

I would like to display numbers with a 0 before when there is only one
char.
For exemple if I gets the number 4, I would like to return 04.

After looking methods on
http://www.ruby-doc.org/core/classes/F..., I don't see how to
process. Of cours it is possible to convert a number into string and
after add a 0, but it's not very friendly.

Thanks for ideas
--
Posted via http://www.ruby-....

3 Answers

Robert Klemme

4/22/2009 10:44:00 AM

0

2009/4/22 Paul A. <cyril.staff@gmail.com>:
> I would like to display numbers with a 0 before when there is only one
> char.
> For exemple if I gets the number 4, I would like to return 04.
>
> After looking methods on
> http://www.ruby-doc.org/core/classes/F..., I don't see how to
> process. Of cours it is possible to convert a number into string and
> after add a 0, but it's not very friendly.

Please look up sprintf, printf and String#%.

Cheers

robert

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestprac...

Marc Heiler

4/22/2009 10:52:00 AM

0

counter = 1; sprintf("%02d", counter) # => "01"

In general, the ruby String class is much better than Int class -
because Strings are like everywhere in ruby. I believe Matz once said
that the String class was most work (or devoured most manhours when he
worked on ruby initially)
--
Posted via http://www.ruby-....

Rimantas Liubertas

4/22/2009 10:58:00 AM

0

>> I would like to display numbers with a 0 before when there is only one
>> char.
>> For exemple if I gets the number 4, I would like to return 04.
>>
>> After looking methods on
>> http://www.ruby-doc.org/core/classes/F..., I don't see how to
>> process. Of cours it is possible to convert a number into string and
>> after add a 0, but it's not very friendly.
>
> Please look up sprintf, printf and String#%.
>

And keep in mind that you will have to convert to string anyway,
because while 07 is fine
08 and 09 are illegal in Ruby=E2=80=94it treats numbers with leading zero a=
s
octal numbers:

>> 7
=3D> 7
>> 07
=3D> 7
>> 8
=3D> 8
>> 08
SyntaxError: (irb):4: Invalid octal digit from /usr/local/bin/irb:12:in `<m=
ain>'

Regards,
Rimantas
--
http://rim...