[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

nicer way to convert array of int to array of string

S Kanakakorn

2/9/2007 8:03:00 PM

Hi,

I'm quite new in Ruby. Here is what I wrote to convert array of
integer to array of string. I'm sure there is more compact and nicer
way to do this. Can I see the "ruby" way here ?

def convert(intArray)
stringArray = []
intArray.each do |i|
stringArray = stringArray + i.to_s.to_a
end
return stringArray
end

Thanks,
--
-Nick Kanakakorn

3 Answers

Stefano Crocco

2/9/2007 8:06:00 PM

0

Alle venerdì 9 febbraio 2007, S Kanakakorn ha scritto:
> Hi,
>
> I'm quite new in Ruby. Here is what I wrote to convert array of
> integer to array of string. I'm sure there is more compact and nicer
> way to do this. Can I see the "ruby" way here ?
>
> def convert(intArray)
> stringArray = []
> intArray.each do |i|
> stringArray = stringArray + i.to_s.to_a
> end
> return stringArray
> end
>
> Thanks,

stringArray=intArray.map{|i| i.to_s}

map passes each value of the array to the block and puts what the block
returns in a array.

Stefano

Daniel Schierbeck

2/9/2007 8:27:00 PM

0

On Sat, 2007-02-10 at 05:02 +0900, S Kanakakorn wrote:
> Hi,
>
> I'm quite new in Ruby. Here is what I wrote to convert array of
> integer to array of string. I'm sure there is more compact and nicer
> way to do this. Can I see the "ruby" way here ?
>
> def convert(intArray)
> stringArray = []
> intArray.each do |i|
> stringArray = stringArray + i.to_s.to_a
> end
> return stringArray
> end

[1, 2, 3, 4].map{|i| i.to_s } #=> ["1", "2", "3", "4"]

#map calls the given block sequentially with each item in the array, and
returns an array containing the values returned by those calls.


Cheers,
Daniel Schierbeck


Jules

2/9/2007 8:29:00 PM

0

On Feb 9, 9:05 pm, Stefano Crocco <stefano.cro...@alice.it> wrote:
> Alle venerdì 9 febbraio 2007, S Kanakakorn ha scritto:
>
> > Hi,
>
> > I'm quite new in Ruby. Here is what I wrote to convert array of
> > integer to array of string. I'm sure there is more compact and nicer
> > way to do this. Can I see the "ruby" way here ?
>
> > def convert(intArray)
> > stringArray = []
> > intArray.each do |i|
> > stringArray = stringArray + i.to_s.to_a
> > end
> > return stringArray
> > end
>
> > Thanks,
>
> stringArray=intArray.map{|i| i.to_s}
>
> map passes each value of the array to the block and puts what the block
> returns in a array.
>
> Stefano

If you use Ruby on Rails or Ruby 1.9 you'll also be able to do this:
intArray.map(&:to_s)