Forum: Ruby Format strings ?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Vlad GALU (Guest)
on 2006-05-23 18:19
(Received via mailing list)
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.
Farrel L. (Guest)
on 2006-05-23 18:25
(Received via mailing list)
Madan M. (Guest)
on 2006-05-23 18:25
(Received via mailing list)
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.
Vlad GALU (Guest)
on 2006-05-23 18:25
(Received via mailing list)
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 :)
James G. (Guest)
on 2006-05-23 18:28
(Received via mailing list)
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"

;)

James Edward G. II
Tim B. (Guest)
on 2006-05-23 18:29
(Received via mailing list)
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
Vlad GALU (Guest)
on 2006-05-23 18:36
(Received via mailing list)
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* :)
Ryan L. (Guest)
on 2006-05-23 19:15
(Received via mailing list)
Another option:

irb(main):001:0> '%04d' % 2
=> "0002"
This topic is locked and can not be replied to.