How to split a delimited string in Ruby and convert it to an array? How to split a delimited string in Ruby and convert it to an array? ruby ruby

How to split a delimited string in Ruby and convert it to an array?


>> "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]


"1,2,3,4".split(",") as strings

"1,2,3,4".split(",").map { |s| s.to_i } as integers


For String Integer without space as String

arr = "12345"arr.split('')output: ["1","2","3","4","5"]

For String Integer with space as String

arr = "1 2 3 4 5"arr.split(' ')output: ["1","2","3","4","5"]

For String Integer without space as Integer

arr = "12345"arr.split('').map(&:to_i)output: [1,2,3,4,5]

For String

arr = "abc"arr.split('')output: ["a","b","c"]

Explanation:

  1. arr -> string which you're going to perform any action.
  2. split() -> is an method, which split the input and store it as array.
  3. '' or ' ' or ',' -> is an value, which is needed to be removed from given string.