Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q13 of 15
Ruby - Class Methods and Variables
What will be the output of this Ruby code?
class Array
  def first_two
    self[0..1]
  end
end

arr = [10, 20, 30, 40]
puts arr.first_two.inspect
A[10]
B[10, 20]
C[20, 30]
Dnil
Step-by-Step Solution
Solution:
  1. Step 1: Understand method added to Array

    The method first_two returns elements at index 0 and 1 using self[0..1].
  2. Step 2: Apply method on given array

    Array is [10, 20, 30, 40], so first_two returns [10, 20].
  3. Final Answer:

    [10, 20] -> Option B
  4. Quick Check:

    Array slice 0..1 = first two elements [OK]
Quick Trick: Slice array 0..1 to get first two elements [OK]
Common Mistakes:
  • Confusing index ranges and getting wrong slice
  • Expecting single element instead of array
  • Thinking method returns nil

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes