[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Convert Integers to Strings

Gary Christopher

1/5/2009 10:44:00 PM

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
--
Posted via http://www.ruby-....

5 Answers

Ryan Davis

1/5/2009 10:56:00 PM

0


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"



Gary Christopher

1/5/2009 11:03:00 PM

0

Thanks mate
--
Posted via http://www.ruby-....

Lars Haugseth

1/6/2009 10:19:00 AM

0

* 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

Gary Christopher

1/6/2009 4:53:00 PM

0

Nice one Lars.

Peace
--
Posted via http://www.ruby-....

JEAN-FRANÇOIS BOLUDOVSKY

1/16/2010 3:33:00 PM

0

Viejo Vizcacha wrote:

> El prop?sito de las grandes potencias en Hait? ha sido el de hacer
> imposible la viabilidad de un rep?blica de mayor?a negra. En eso han
> sido exitosas.

Que estupidez. Republicas de mayoria negra las hay a patadas en
Africa, y la mayoria son tambien estados fallidos como Haiti.

BOLU