0
0
Rubyprogramming~20 mins

Why methods always return a value in Ruby - Challenge Your Understanding

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?
Ruby
def greet(name)
  message = "Hello, "+name
  message
end

greet("Alice")
A"Hello, Alice"
Bnil
C"message"
DSyntaxError
Attempts:
2 left
💡 Hint
In Ruby, the last evaluated expression is returned automatically.
🧠 Conceptual
intermediate
1: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?
ABecause Ruby automatically returns the value of the last evaluated expression in the method.
BBecause Ruby methods must have an explicit return statement to return a value.
CBecause Ruby methods return nil by default if no return is given.
DBecause Ruby methods return the first expression evaluated.
Attempts:
2 left
💡 Hint
Think about what Ruby does with the last line inside a method.
🔧 Debug
advanced
2: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)
A5
BSyntaxError
CDone
Dnil
Attempts:
2 left
💡 Hint
Remember Ruby returns the last evaluated expression.
📝 Syntax
advanced
1:30remaining
Which method returns nil?
Which of these Ruby methods returns nil when called?
A
def example
  x = 10
end
B
def example
  5
  6
end
C
def example
  return nil
end
D
def example
  return
end
Attempts:
2 left
💡 Hint
Consider what happens when return is called without a value.
🚀 Application
expert
2: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
A"x is greater"
B3
Cnil
Dfalse
Attempts:
2 left
💡 Hint
Look at the if-else and what the last evaluated expression is.