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
greet(name, greeting = "Hello", shout: false):"Hello, Ana", or withshout: true, upper-case with!:"HELLO, ANA!".repeat_with_index(items): yields each item and its position to the block.timed: runs the block, printsTook ...(any time measurement is fine), and returns the block's result.