Thursday, January 17, 2008

Converts a comma separated string of numbers into an array of integers

This is all there is to convert a string of comma separated integers to an array of integers.

>> "1,24,53,6,23,6,5".split(",").collect{ |s| s.to_i }
=> [1, 24, 53, 6, 23, 6, 5]

This is why Ruby is so fun to use. Is there a shorter way to do this than what I have?

5 comments:

Anonymous said...

possibly just doing %w(1,24,53,6,23,6,5)

Conrad said...

%w(1,24,53,6,23,6,5) is the reverse of what I did.

>%w(1,24,53,6,23,6,5)
=> ["1,24,53,6,23,6,5"]

Anonymous said...

%w does not result in the ability to traverse through the array.

>> %w(1,24,53,6,23,6,5).length
=> 1

where

>>"1,24,53,6,23,6,5".split(",").collect{ |s| s.to_i }.length
=> 7

Anonymous said...

> %w(1,24,53,6,23,6,5) is the reverse of what I did.

The main problem with the first comment's example: %w() should use whitespaces rather than commas:

> %w(1 24 53 6 23 6 5)
=> ["1", "24", "53", "6", "23", "6", "5"]

Still, this returns Strings, so you can call map {|s| s.to} to get the same results..
not sure this is relevant though..

Anonymous said...

"1,24,53,6,23,6,5".split(",").map(&:to_i)