w3resource

Ruby Array Exercises: Split a delimited string into an array

Ruby Array: Exercise-10 with Solution

Write a Ruby program to split a delimited string into an array.

Ruby Array Exercises: Split a delimited string into an array

Ruby Code:

color = "Red, Green, Blue, White"
nums = "1, 3, 4, 5, 7"
print "Original delimited string:\n"
print color,", "
print nums
print "\nString to array:\n"
color_array = color.split(",")
nums_array = nums.split(",").map { |s| s.to_i }
print color_array
print "\n",nums_array

Output:

Original delimited string:
Red, Green, Blue, White1, 3, 4, 5, 7String to array:
["Red", " Green", " Blue", " White"]
[1, 3, 4, 5, 7]

Flowchart:

Flowchart: Split a delimited string into an array

Ruby Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Ruby program to compute the sum of all the elements. The array length must be 3 or more.
Next: Write a Ruby program to create an array with the elements "rotated left" of an given array of integers length 3.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/ruby-exercises/array/ruby-array-exercise-10.php