Chapter 5 - Arrays and Blocks

Exercise 1: Converting a String to an Array and back

We have a string that’s supposed to contain a list of fruit, separated by commas. But there are some items in there that shouldn’t be. Write a script that does the following:

  • Use the split method with an argument of ", " to split the string into an array.
  • Use the pop method to discard the last array element.
  • Use the shift method to discard the first array element.
  • Use the join method with an argument of ", " to join the array back into a string, and print the result.

Solution

fruit_string = "boulder, apple, banana, peach, cow"
fruit = fruit_string.split(", ")
fruit.pop
fruit.shift
puts fruit.join(", ")