Bird
0
0

What will this code print?

medium📝 Predict Output Q5 of 15
Ruby - Class Methods and Variables
What will this code print?
class Array
  def second
    self[1]
  end
end

arr = [10, 20, 30]
puts arr.second
A10
B20
C30
DError: undefined method second
Step-by-Step Solution
Solution:
  1. Step 1: Understand the reopened Array class

    The second method returns the element at index 1.
  2. Step 2: Apply the method to the array [10, 20, 30]

    The element at index 1 is 20, so arr.second returns 20.
  3. Final Answer:

    20 -> Option B
  4. Quick Check:

    Array second element = 20 [OK]
Quick Trick: Index 1 is the second element in arrays [OK]
Common Mistakes:
  • Confusing index 0 and 1
  • Expecting error for new method

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes