0
0
Rubyprogramming~20 mins

Method declaration with def in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Method Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a simple method call
What is the output of this Ruby code?
Ruby
def greet(name)
  "Hello, #{name}!"
end

puts greet("Alice")
Agreet
BHello, Alice!
CHello, name!
Dnil
Attempts:
2 left
💡 Hint
Look at how the method uses string interpolation with the parameter.
Predict Output
intermediate
2:00remaining
Return value of method without explicit return
What does this Ruby method return when called with argument 5?
Ruby
def square(x)
  x * x
end

result = square(5)
puts result
ASyntaxError
B5
Cnil
D25
Attempts:
2 left
💡 Hint
In Ruby, the last evaluated expression is returned by default.
🔧 Debug
advanced
2:00remaining
Identify the error in method declaration
What error does this Ruby code produce?
Ruby
def add_numbers(a, b)
  sum = a + b
  puts sum
end

add_numbers(3, 4)
ANo error, outputs 7
BNoMethodError: undefined method 'add_numbers'
CTypeError: no implicit conversion of nil into Integer
DSyntaxError: unexpected end-of-input, expecting keyword_end
Attempts:
2 left
💡 Hint
Check if all method definitions are properly closed.
Predict Output
advanced
2:00remaining
Method with default parameter value
What is the output of this Ruby code?
Ruby
def greet(name = "Guest")
  "Welcome, #{name}!"
end

puts greet
puts greet("Bob")
A
Welcome, Guest!
Welcome, Bob!
B
Welcome, !
Welcome, Bob!
C
Welcome, Guest!
Welcome, Guest!
DSyntaxError
Attempts:
2 left
💡 Hint
Look at the default value assigned to the parameter.
🧠 Conceptual
expert
2:00remaining
Understanding method scope and variable visibility
Consider this Ruby code. What is the output?
Ruby
def change_var(x)
  x = 10
end

value = 5
change_var(value)
puts value
Anil
B10
C5
DNameError
Attempts:
2 left
💡 Hint
Think about whether the method changes the original variable or just a copy.