Chapter 6 - Block return values

Exercise 1: Using a block return value in a method

Below is a method named bar_chart. We’re going to use “string multiplication” ("$" * 3 returns "$$$", for example) to make a primitive bar chart, using the return values from a block. Fill in the missing line of code in the middle of the each block to yield value to a block, and “multiply” the string "$" by the block return value. Then print the result.

def bar_chart(array)
  array.each do |value|
    # YOUR CODE HERE
  end
end

array = [1, 2, 3, 4, 5]

puts "Multiplication:"
# The next line of code should print:
# $$$
# $$$$$$
# $$$$$$$$$
# $$$$$$$$$$$$
# $$$$$$$$$$$$$$$
bar_chart(array) { |number| 3 * number }

puts "Division:"
# The next line of code should print:
# $$$$$$$$$$$$$$$$$$$$
# $$$$$$$$$$
# $$$$$$
# $$$$$
# $$$$
bar_chart(array) { |number| 20.0 / number }

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

Exercise 2: IRB session

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

> numbers = [1, 2, 3, 4, 5]
> numbers.find { |number| number > 2 }
> numbers.find_all { |number| number > 2 }
> numbers.map { |number| "$" * number }
> numbers.reject { |number| number > 2 }
> numbers.partition { |number| number > 2 }
> strings = ["Ruby", "is", "so", "cool"]
> strings.find { |string| string.length > 2 }
> strings.find_all { |string| string.length > 2 }
> strings.reject { |string| string.length > 2 }
> strings.partition { |string| string.length > 2 }

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