Complete the code to print each number using a block.
numbers = [1, 2, 3] numbers.each [1] |num| puts num end
The do keyword starts a block in Ruby, which is used here with each to print each number.
Complete the code to yield control to the block with a value.
def greet yield [1] end greet { |name| puts "Hello, #{name}!" }
The yield keyword passes control to the block, sending the value "Ruby" as an argument.
Fix the error in the block syntax to correctly sum numbers.
sum = 0 [1, 2, 3].each [1] |n| sum += n end puts sum
The do keyword correctly starts the block for the each method to sum the numbers.
Complete the code to create a hash with word lengths for words longer than 3 letters.
words = ["cat", "house", "tree", "a"] lengths = { word=> [1] for word in words if len(word) > 3 }
In Ruby, the hash key-value pair uses =>. The length of the word is obtained by len(word) (though in Ruby it should be word.length, this exercise uses len for simplicity).
Fill all three blanks to create a hash of uppercase words and their lengths for words longer than 2 letters.
words = ["dog", "cat", "a", "bird"] result = { [1]: [2] for w in words if w.length [3] 2 }
The hash uses the uppercase word as key (w.upcase), the length as value (w.length), and filters words longer than 2 letters (>).