Challenge - 5 Problems
Ruby Return Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Ruby method?
Consider this Ruby method. What will it return when called?
Ruby
def greet(name) message = "Hello, "+name message end greet("Alice")
Attempts:
2 left
💡 Hint
In Ruby, the last evaluated expression is returned automatically.
✗ Incorrect
Ruby methods return the value of the last expression evaluated if no explicit return is used. Here, the last line is the string concatenation stored in 'message', so it returns "Hello, Alice".
🧠 Conceptual
intermediate1:30remaining
Why do Ruby methods always return a value?
Why does every method in Ruby always return a value, even if no return statement is used?
Attempts:
2 left
💡 Hint
Think about what Ruby does with the last line inside a method.
✗ Incorrect
Ruby methods return the value of the last expression evaluated automatically. This means even without a return statement, the method returns something.
🔧 Debug
advanced2:00remaining
What is the output and why?
Look at this Ruby code. What will be printed and why?
Ruby
def add(a, b) sum = a + b sum "Done" end puts add(2, 3)
Attempts:
2 left
💡 Hint
Remember Ruby returns the last evaluated expression.
✗ Incorrect
The method evaluates 'sum = a + b' (which is 5), then 'sum' (5), then the string "Done". The last expression is "Done", so the method returns "Done".
📝 Syntax
advanced1:30remaining
Which method returns nil?
Which of these Ruby methods returns nil when called?
Attempts:
2 left
💡 Hint
Consider what happens when return is called without a value.
✗ Incorrect
In Ruby, 'return' without a value returns nil. Option D returns 10 (last expression), Option D returns 6 (last expression), Option D returns nil explicitly, Option D returns nil because of bare 'return'.
🚀 Application
expert2:30remaining
What is the value of result after this method call?
Given this Ruby method, what is the value of 'result' after calling 'calculate'?
Ruby
def calculate x = 1 y = 2 if x > y "x is greater" else x + y end end result = calculate
Attempts:
2 left
💡 Hint
Look at the if-else and what the last evaluated expression is.
✗ Incorrect
Since x (1) is not greater than y (2), the else branch runs, returning x + y which is 3. This is the last evaluated expression, so the method returns 3.