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.
D1be1ff625c6286f4734cb6019490301?d=identicon&s=25 Vlad GALU (Guest)
on 2006-05-23 16: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.
05be5d6610e2c3f1780aa0e39e902e93?d=identicon&s=25 Farrel Lifson (Guest)
on 2006-05-23 16:25
(Received via mailing list)
508bca331a21d64d298561f1079b4113?d=identicon&s=25 Madan Manoharan (Guest)
on 2006-05-23 16:25
(Received via mailing list)
On 5/23/06, Vlad GALU <vladgalu@gmail.com> 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.
D1be1ff625c6286f4734cb6019490301?d=identicon&s=25 Vlad GALU (Guest)
on 2006-05-23 16:25
(Received via mailing list)
On 5/23/06, Vlad GALU <vladgalu@gmail.com> 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 :)
4299e35bacef054df40583da2d51edea?d=identicon&s=25 James Gray (bbazzarrakk)
on 2006-05-23 16: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 Gray II
62002cee15efcf4628cd7efc19425a07?d=identicon&s=25 Tim Becker (Guest)
on 2006-05-23 16:29
(Received via mailing list)
On 5/23/06, Vlad GALU <vladgalu@gmail.com> 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
D1be1ff625c6286f4734cb6019490301?d=identicon&s=25 Vlad GALU (Guest)
on 2006-05-23 16:36
(Received via mailing list)
On 5/23/06, Tim Becker <a2800276@gmail.com> wrote:
> On 5/23/06, Vlad GALU <vladgalu@gmail.com> 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* :)
4b174722d1b1a4bbd9672e1ab50c30a9?d=identicon&s=25 Ryan Leavengood (Guest)
on 2006-05-23 17:15
(Received via mailing list)
Another option:

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