Lars Haugseth
1/6/2009 10:19:00 AM
* Ryan Davis <ryand-ruby@zenspider.com> wrote:
>
> On Jan 5, 2009, at 14:43 , Gary Christopher wrote:
>
> > Should I create a hash of {1 => "one".....} and then iterate through
> > the
> > input, swapping digits that match a key with the key's value.
>
> yes but... gsub is much easier
>
> > >> numbers = { "1" => "one" }
> > => {"1"=>"one"}
> > >> 111.to_s.gsub(/\d/) { |n| numbers[n] }
> > => "oneoneone"
I'd rather use an array than a hash in this case:
>> numbers = %w(zero one two three four five six seven eight nine)
=> ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
>> 2009.to_s.gsub(/\d/) { |n| numbers[n.to_i] }
=> "twozerozeronine"
--
Lars Haugseth
"If anyone disagrees with anything I say, I am quite prepared not only to
retract it, but also to deny under oath that I ever said it." -Tom Lehrer