How to split a delimited string in Ruby and convert it to an array?
ArraysRubyStringSplitArrays Problem Overview
I have a string
"1,2,3,4"
and I'd like to convert it into an array:
[1,2,3,4]
How?
Arrays Solutions
Solution 1 - Arrays
>> "1,2,3,4".split(",")
=> ["1", "2", "3", "4"]
Or for integers:
>> "1,2,3,4".split(",").map { |s| s.to_i }
=> [1, 2, 3, 4]
Or for later versions of ruby (>= 1.9 - as pointed out by Alex):
>> "1,2,3,4".split(",").map(&:to_i)
=> [1, 2, 3, 4]
Solution 2 - Arrays
"1,2,3,4".split(",")
as strings
"1,2,3,4".split(",").map { |s| s.to_i }
as integers
Solution 3 - Arrays
String Integer
without space as String
For arr = "12345"
arr.split('')
output: ["1","2","3","4","5"]
String Integer
with space as String
For arr = "1 2 3 4 5"
arr.split(' ')
output: ["1","2","3","4","5"]
String Integer
without space as Integer
For arr = "12345"
arr.split('').map(&:to_i)
output: [1,2,3,4,5]
For String
arr = "abc"
arr.split('')
output: ["a","b","c"]
Explanation:
arr
-> string which you're going to perform any action.split()
-> is an method, which split the input and store it as array.''
or' '
or','
-> is an value, which is needed to be removed from given string.
Solution 4 - Arrays
"12345".each_char.map(&:to_i)
each_char
does basically the same as split('')
: It splits a string into an array of its characters.
hmmm, I just realize now that in the original question the string contains commas, so my answer is not really helpful ;-(..
Solution 5 - Arrays
the simplest way to convert a string that has a delimiter like a comma is just to use the split method
"1,2,3,4".split(',') # "1", "2", "3", "4"]
you can find more info on how to use the split method in the ruby docs
> Divides str into substrings based on a delimiter, returning an array > of these substrings. > > If pattern is a String, then its contents are used as the delimiter > when splitting str. If pattern is a single space, str is split on > whitespace, with leading whitespace and runs of contiguous whitespace > characters ignored. > > If pattern is a Regexp, str is divided where the pattern matches. > Whenever the pattern matches a zero-length string, str is split into > individual characters. If pattern contains groups, the respective > matches will be returned in the array as well. > > If pattern is omitted, the value of $; is used. If $; is nil (which is > the default), str is split on whitespace as if ` ‘ were specified. > > If the limit parameter is omitted, trailing null fields are > suppressed. If limit is a positive number, at most that number of > fields will be returned (if limit is 1, the entire string is returned > as the only entry in an array). If negative, there is no limit to the > number of fields returned, and trailing null fields are not > suppressed.