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/Fixnum.html, 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.
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/Fixnum.html, 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.
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/Fixnum.html, 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.
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)
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/Fixnum.html, 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—it treats numbers with leading zero as
octal numbers:
7
=> 7
07
=> 7
8
=> 8
08
SyntaxError: (irb):4: Invalid octal digit from /usr/local/bin/irb:12:in `<main>'
Dan's suggestion is the simplest. But I want to point out that you can
add a Fixnum method yourself, if you are so inclined:
class Fixnum
def to_formatted_s
"%02d" % self
end
end
puts 7.to_formatted_s
···
On Apr 22, 6:58 am, "DanDiebolt.exe" <dandieb...@yahoo.com> wrote:
[Note: parts of this message were removed to make it a legal post.]
irb(main):001:0> n=7
=> 7
irb(main):002:0> "%02d" % n
=> "07"
--- On Wed, 4/22/09, Paul A. <cyril.st...@gmail.com> wrote:
From: Paul A. <cyril.st...@gmail.com>
Subject: [noob question] convert 7 in 07
To: "ruby-talk ML" <ruby-t...@ruby-lang.org>
Date: Wednesday, April 22, 2009, 6:39 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 onhttp://www.ruby-doc.org/core/classes/Fixnum.html, I don't see how to
process.