Lesson 6 of 8 · 10 min

Methods that take blocks

Arguments

Methods can have default values and keyword arguments (named arguments, given with a colon):

def order(item, quantity = 1, gift_wrap: false)
  text = "#{quantity} x #{item}"
  text += " (gift wrapped)" if gift_wrap
  text
end

order("pen")                       # "1 x pen"
order("pen", 3, gift_wrap: true)   # "3 x pen (gift wrapped)"

The last line's value is returned automatically; return is only needed to leave early.

yield: methods that take a block

Any method can be given a block. Inside the method, yield runs it, passing values in:

def twice
  yield
  yield
end

twice { puts "Hi" }    # prints Hi two times

def each_pair_sum(numbers)
  numbers.each_cons(2) { |a, b| yield(a + b) }
end

each_pair_sum([1, 2, 3]) { |s| puts s }   # 3, 5

yield returns whatever the block returns, so a method can use the block's answer. block_given? tells you whether a block was passed.

This is how Ruby's own each, map and times work.

Your task

  1. greet(name, greeting = "Hello", shout: false): "Hello, Ana", or with shout: true, upper-case with !: "HELLO, ANA!".
  2. repeat_with_index(items): yields each item and its position to the block.
  3. timed: runs the block, prints Took ... (any time measurement is fine), and returns the block's result.
main.rb
def greet(name)
end

def repeat_with_index(items)
end

def timed
end

repeat_with_index(%w[mango guava]) { |fruit, i| puts "#{i + 1}. #{fruit}" }

Ruby 3.4 runs right here in your browser. The first run downloads about 16 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…