nicer way to convert array of int to array of string

S

S Kanakakorn

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,
 
S

Stefano Crocco

Alle venerd=EC 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 =3D []
intArray.each do |i|
stringArray =3D stringArray + i.to_s.to_a
end
return stringArray
end

Thanks,

stringArray=3DintArray.map{|i| i.to_s}

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

Stefano
 
D

Daniel Schierbeck

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
 
J

Jules

Alle venerdì 9 febbraio 2007, S Kanakakorn ha scritto:
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

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)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top