Format strings?


#1

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.


#2

Kernel#sprintf ?

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


#3

On 5/23/06, Vlad GALU removed_email_address@domain.invalid 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.


#4

On 5/23/06, Vlad GALU removed_email_address@domain.invalid 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:


#5

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


#6

On 5/23/06, Vlad GALU removed_email_address@domain.invalid 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


#7

Another option:

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


#8

On 5/23/06, Tim B. removed_email_address@domain.invalid wrote:

On 5/23/06, Vlad GALU removed_email_address@domain.invalid 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: