0
0
Rubyprogramming~20 mins

Implicit return (last expression) in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Return Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Ruby method?
Consider this Ruby method. What will it return when called with calculate(5)?
Ruby
def calculate(x)
  y = x * 2
  y + 3
end

calculate(5)
A10
B8
Cnil
D13
Attempts:
2 left
💡 Hint
Remember, Ruby methods return the value of the last expression automatically.
Predict Output
intermediate
2:00remaining
What does this Ruby method return?
Look at this method and tell what it returns when called with greet('Alice').
Ruby
def greet(name)
  message = "Hello, " + name
  message.upcase
end

greet('Alice')
A"HELLO, ALICE"
B"hello, alice"
Cnil
D"Hello, Alice"
Attempts:
2 left
💡 Hint
The last expression is message.upcase, which changes the string to uppercase.
🔧 Debug
advanced
2:00remaining
Why does this method return nil?
This method is supposed to return the doubled value of num, but it returns nil. Why?
Ruby
def double(num)
  result = num * 2
  puts result
end

double(4)
ABecause <code>num</code> is not passed to the method
BBecause <code>puts</code> returns nil and it is the last expression in the method
CBecause <code>result</code> is not assigned correctly
DBecause the method has no return statement
Attempts:
2 left
💡 Hint
Check what puts returns in Ruby.
🧠 Conceptual
advanced
2:00remaining
What value does this method return?
Given this method, what is the return value when called with status_check(true)?
Ruby
def status_check(flag)
  if flag
    "Success"
  else
    "Failure"
  end
end

status_check(true)
Atrue
B"Failure"
C"Success"
Dnil
Attempts:
2 left
💡 Hint
The last expression executed depends on the condition.
Predict Output
expert
2:00remaining
What is the output of this Ruby code?
What does this method return when called with process(3)?
Ruby
def process(n)
  n.times do |i|
    return i if i == 2
  end
  10
end

process(3)
A2
B3
C10
Dnil
Attempts:
2 left
💡 Hint
The method uses an explicit return inside a loop.