Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 462
user3466773 Avatar asked Dec 04 '25 17:12

user3466773


1 Answers

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 
like image 145
daremkd Avatar answered Dec 06 '25 07:12

daremkd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!