0
0
Rubyprogramming~10 mins

Why blocks are fundamental to Ruby - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to print each number using a block.

Ruby
numbers = [1, 2, 3]
numbers.each [1] |num| puts num end
Drag options to blanks, or click blank then click option'
Ado
Bif
Cwhile
Dfor
Attempts:
3 left
💡 Hint
Common Mistakes
Using keywords like if or while instead of do to start a block.
Omitting the block entirely.
2fill in blank
medium

Complete the code to yield control to the block with a value.

Ruby
def greet
  yield [1]
end

greet { |name| puts "Hello, #{name}!" }
Drag options to blanks, or click blank then click option'
Aself
B"Ruby"
Cblock
Dname
Attempts:
3 left
💡 Hint
Common Mistakes
Passing a variable name that is not defined.
Not passing any value to yield.
3fill in blank
hard

Fix the error in the block syntax to correctly sum numbers.

Ruby
sum = 0
[1, 2, 3].each [1] |n| sum += n end
puts sum
Drag options to blanks, or click blank then click option'
Ado
Bif
Cwhile
Dfor
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect keywords like if or while to start a block.
Missing the block entirely.
4fill in blank
hard

Complete the code to create a hash with word lengths for words longer than 3 letters.

Ruby
words = ["cat", "house", "tree", "a"]
lengths = { word=> [1] for word in words if len(word) > 3 }
Drag options to blanks, or click blank then click option'
A:
Blen(word)
Clength
D=>
Attempts:
3 left
💡 Hint
Common Mistakes
Using colon (:) instead of => for hash key-value pairs.
Using incorrect method names for length.
5fill in blank
hard

Fill all three blanks to create a hash of uppercase words and their lengths for words longer than 2 letters.

Ruby
words = ["dog", "cat", "a", "bird"]
result = { [1]: [2] for w in words if w.length [3] 2 }
Drag options to blanks, or click blank then click option'
Aw.upcase
Bw.length
C>
Dw.downcase
Attempts:
3 left
💡 Hint
Common Mistakes
Using downcase instead of upcase for keys.
Using incorrect comparison operators.