Format strings?

Having an int object, let’s say the value is 2, I’d like to print
it out as “0002”. I miss C’s format strings. Any hints ? Thanks in
advance.

Kernel#sprintf ?

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

On 5/23/06, Vlad GALU [email protected] wrote:

Having an int object, let’s say the value is 2, I’d like to print
it out as “0002”. I miss C’s format strings. Any hints ? Thanks in
advance.

def format3(int)
fmtStr = sprintf(“%04d”, int)
print “#{fmtStr}\n”
end

format3(2)

-Madan.

On 5/23/06, Vlad GALU [email protected] wrote:

Having an int object, let’s say the value is 2, I’d like to print
it out as “0002”. I miss C’s format strings. Any hints ? Thanks in
advance.

Ah I found Kernel#printf, sorry for the noise :slight_smile:

On May 23, 2006, at 9:16 AM, Vlad GALU wrote:

Having an int object, let’s say the value is 2, I’d like to print
it out as “0002”. I miss C’s format strings. Any hints ? Thanks in
advance.

Miss them no longer:

value = 2
=> 2

sprintf “%04d”, value
=> “0002”

“%04d” % value
=> “0002”

:wink:

James Edward G. II

On 5/23/06, Vlad GALU [email protected] wrote:

Having an int object, let’s say the value is 2, I’d like to print
it out as “0002”. I miss C’s format strings.

printf “%04d”, 2

Ruby has format strings!
-tim

Another option:

irb(main):001:0> ‘%04d’ % 2
=> “0002”

On 5/23/06, Tim B. [email protected] wrote:

On 5/23/06, Vlad GALU [email protected] wrote:

Having an int object, let’s say the value is 2, I’d like to print
it out as “0002”. I miss C’s format strings.

printf “%04d”, 2

Ruby has format strings!
-tim

Thank you all! I noticed soon after I posted the question blush :slight_smile: