Step 1: Understand the method and block interaction
The method greet calls yield with the string 'Ruby', which passes it to the block parameter 'name'.
Step 2: Evaluate the block execution
The block prints "Hello, #{name}!" where name is 'Ruby', so it prints "Hello, Ruby!".
Final Answer:
Hello, Ruby! -> Option C
Quick Check:
yield passes 'Ruby' to block [OK]
Hint: yield runs block with given argument [OK]
Common Mistakes:
Thinking yield returns method name
Confusing block parameter with string literal
Expecting syntax error due to yield
4. Identify the error in this Ruby code:
def repeat
3.times do
yield
end
end
repeat { puts 'Hi' }
medium
A. SyntaxError due to missing block parameter
B. Method repeat is undefined
C. RuntimeError because yield has no block
D. No error, code runs and prints 'Hi' three times
Solution
Step 1: Analyze the method definition
The method repeat calls 3.times and yields to the block each time.
Step 2: Check the block passed to repeat
The block prints 'Hi', so it will print 'Hi' three times without error.
Final Answer:
No error, code runs and prints 'Hi' three times -> Option D
Quick Check:
yield with block runs fine [OK]
Hint: yield needs a block; here block is given [OK]
Common Mistakes:
Assuming yield needs parameters
Thinking missing block parameter causes error
Confusing method name with undefined
5. How can blocks make Ruby code more flexible? Choose the best explanation.
hard
A. Blocks allow methods to accept custom code to run, changing behavior without rewriting methods
B. Blocks store data permanently for later use
C. Blocks replace variables to save memory
D. Blocks automatically optimize code speed
Solution
Step 1: Understand the role of blocks in flexibility
Blocks let methods run different code passed by the user, so methods can do many tasks without changing their code.
Step 2: Evaluate the options
Blocks allow methods to accept custom code to run, changing behavior without rewriting methods. This is the best explanation. The other choices are wrong: blocks do not replace variables to save memory, store data permanently for later use, or automatically optimize code speed.
Final Answer:
Blocks allow methods to accept custom code to run, changing behavior without rewriting methods -> Option A
Quick Check:
Blocks = flexible method behavior [OK]
Hint: Blocks let methods run custom code passed in [OK]
Common Mistakes:
Thinking blocks store data like variables
Believing blocks speed up code automatically
Confusing blocks with memory management
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.