Chapter 5 - Arrays and Blocks

Exercise 1: Converting a String to an Array and back

This string is supposed to contain a list of fruit, separated by commas. But there are some items in there that shouldn’t be:

fruit_string = "boulder, apple, banana, peach, cow"

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.

You should get the following output:

apple, banana, peach

When you’re ready, have a look at the solution.

Exercise 2: Yielding to a block

Write a method named with_these_numbers so that the following code will work:

with_these_numbers(1, 4) do |first, second|
  puts first + second # Output: 5
end

with_these_numbers(3, 6) do |first, second|
  puts first * second # Output: 18
end

with_these_numbers(12, 3) do |first, second|
  puts first / second # Output: 4
end

Some hints:

  • Your method will need to accept two parameters.
  • Your finished method body will probably be a single line of code.
  • You’ll need to use the yield keyword within the method body, to yield to the block.
  • You’ll need to pass the two method parameters as arguments to yield, so that they’re passed on to the block.

When you’re ready, have a look at the solution.

Exercise 3: IRB session

Launch irb from your terminal, and try the following expressions:

> numbers = [3, 29, 5, 12, 18]
> numbers.each { |number| puts number * number }
> numbers.each { |number| puts number.odd? }
> numbers.each { |number| puts "$" * number }
> strings = ["I", "ma", "a", "ybuR", "retsam"]
> strings.each { |string| puts string.reverse }
> strings.each { |string| puts string.length }

After you try them out, you can see an explanation of the results.