Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q5 of 15
Ruby - Methods
What will be the output of this Ruby code?
def power(base, exponent = 2)
  base ** exponent
end

puts power(3)
puts power(3, 4)
A3 4
B6 7
C9 81
DError due to missing argument
Step-by-Step Solution
Solution:
  1. Step 1: Understand default parameter

    The method power has a default exponent of 2.
  2. Step 2: Evaluate power(3)

    Since exponent is not provided, it defaults to 2, so 3 ** 2 = 9.
  3. Step 3: Evaluate power(3, 4)

    Exponent is provided as 4, so 3 ** 4 = 81.
  4. Final Answer:

    9 81 -> Option C
  5. Quick Check:

    Default exponent used when missing, explicit exponent otherwise [OK]
Quick Trick: Default exponent used if argument missing [OK]
Common Mistakes:
MISTAKES
  • Assuming missing argument causes error
  • Confusing multiplication with exponentiation
  • Ignoring default parameter value

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes