Search code examples
rubyarraysclassinstance-methodssplat

Find the 2nd element of array


I don't understand how this isn't working. The program is supposed to take instance method second in the class Array and return the 2nd object in the array

class Array
  def second(*arr)
  arr.length <= 1 ? nil : arr[1]
  end
end

#Test cases
Test.assert_equals(Array([1, 2, 3]), 2,) #Getting nil
Test.assert_equals(Array([]), nil) #passes
Test.assert_equals(Array([1]), nil) #passes

What am I doing wrong? if I remove class Array and test on second it works fine?


Solution

  • Why use *arr? If you're monkey-patching Array, then use self:

    class Array
      def second
        self.length <= 1 ? nil : self[1]
      end
    end
    
    p [1,2,3].second #=> 2
    p [1].second #=> nil
    p [].second #=> nil