Forum: Ruby Convert Integers to 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.
9b419736f944aade48b85ae3244596c6?d=identicon&s=25 Gary Chris (rlzyoner)
on 2009-01-05 23:42
Howdy,

New to Ruby and looking for some help.
I would like to prompt the user for input String of single [0 - 9 incl]
digits e.g 57
and convert these to word format and store as a single string e.g
fiveseven

What way is best to go about doing this.

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.

Thanks a lot
5a837592409354297424994e8d62f722?d=identicon&s=25 Ryan Davis (Guest)
on 2009-01-05 23:57
(Received via mailing list)
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
9b419736f944aade48b85ae3244596c6?d=identicon&s=25 Gary Chris (rlzyoner)
on 2009-01-06 00:00
Thanks mate
E67536b7234fcf4e0c01b100826cfc60?d=identicon&s=25 Lars Haugseth (Guest)
on 2009-01-06 11:55
(Received via mailing list)
* Ryan Davis <ryand-ruby@zenspider.com> wrote:
> > => {"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
9b419736f944aade48b85ae3244596c6?d=identicon&s=25 Gary Chris (rlzyoner)
on 2009-01-06 17:52
Nice one Lars.

Peace
This topic is locked and can not be replied to.