Kent Sibilev
2/9/2006 2:26:00 AM
Or
irb(main):001:0> class Integer
irb(main):002:1> def commify
irb(main):003:2> self.to_s.gsub(/(\d)(?=(\d{3})+$)/,'\1,')
irb(main):004:2> end
irb(main):005:1> end
=> nil
irb(main):006:0> 1000.commify
=> "1,000"
irb(main):007:0> 100.commify
=> "100"
irb(main):008:0> 1_000_000.commify
=> "1,000,000"
irb(main):009:0> 1024.commify
=> "1,024"
Kent
On 2/8/06, Logan Capaldo <logancapaldo@gmail.com> wrote:
>
> On Feb 8, 2006, at 8:43 PM, HH wrote:
>
> > This has got to be simple but I checked the PickAxe and Google to
> > no avail.
> > My guess is that I'm looking for it in terms that don't make sense.
> >
> > Anyway...
> >
> > I have a fixnum:
> >
> > a = 1000
> >
> > I would like to output it with a comma, such as "1,000". Is there a
> > formatting class or something I can use something along these lines
> > (thinking from my Java background):
> >
> > Formatter f = Formatter.new("N0")
> > puts f(a)
> >
> > Any help appreciated.
> >
> > Thanks,
> > Hunter
> >
> >
> >
>
> I dunno know about some kind of builtin format object (I imagine
> maybe the right incantation of sprintf could do it) but heres a
> method (kinda long for what it is, theres probably some regex to do
> it in one fell swoop):
>
> % cat commify.rb
> require 'enumerator'
> def commify(num)
> str = num.to_s
> a = []
> str.split(//).reverse.each_slice(3) { |slice| a << slice }
> new_a = []
> a.each do |item|
> new_a << item
> new_a << [","]
> end
> new_a.delete_at(new_a.length - 1)
> new_a.flatten.reverse.join
> end
>
> p commify(1000)
> p commify(100)
> p commify(1_000_000)
> p commify(1024)
>
> % ruby commify.rb
> "1,000"
> "100"
> "1,000,000"
> "1,024"
>
>
>