Stochastic Nonsense

Put something smart here.

Formatted Numbers in Ruby

In C or C++, it’s can be a pain to get thousands separators in printf. In ruby, it can be trivial, as long as you use the right libraries. If you have ActiveSupport installed (which I believe comes with Rails), you’re all set. Note that you don’t have to be using Rails; this will work in a plain ruby script.

1
2
3
4
5
6
7
8
9
$ irb
irb(main):001:0> require 'action_view'
=> true
irb(main):002:0> include ActionView::Helpers::NumberHelper
=> Object
irb(main):003:0> number_with_delimiter(123456)
=> "123,456"
irb(main):004:0> number_to_human(123456)
=> "123 Thousand"

number_with_delimiter is great, and number_to_human is a nice bonus.

For the record, software versions and the install command:

1
2
3
4
5
$ ruby --version
ruby 1.9.2p180 (2011-02-18 revision 30909) [x86_64-darwin10.7.4]
$ gem --version
1.3.7
$ gem install actionpack