Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to check if a block is given.
Ruby
def greet if [1] yield else puts "No block given" end end
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using block_given without the question mark
Using block? which is not a Ruby method
Using given_block? which does not exist
✗ Incorrect
The method block_given? returns true if a block is passed to the method.
2fill in blank
mediumComplete the code to print a message only if a block is given.
Ruby
def check puts "Block is given" if [1] end
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting the question mark in block_given?
Using block_given without parentheses
✗ Incorrect
block_given? returns true if a block is passed, so the message prints only then.
3fill in blank
hardFix the error in the code to correctly check for a block.
Ruby
def run if [1] yield else puts "No block" end end
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using block_given without question mark
Using block? which is not a Ruby method
✗ Incorrect
block_given? is the correct method to check if a block is passed.
4fill in blank
hardFill both blanks to create a hash with word lengths only if block is given and length > 3.
Ruby
lengths = {word: [1] for word in words if [2] Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using block_given? as a condition inside the hash comprehension
Using yield incorrectly in the hash comprehension
✗ Incorrect
We want the length of each word as the value and only include words longer than 3 characters.
5fill in blank
hardFill all three blanks to create a hash with uppercase keys and values only if block is given and value > 0.
Ruby
result = { [1]: [2] for [3], v in data.items() if block_given? && v > 0 } Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using key instead of k as loop variable
Not converting keys to uppercase
Using block_given? incorrectly in the comprehension
✗ Incorrect
Keys are converted to uppercase with k.upcase, values are v, and the loop variables are k and v.