Ruby: remove first and last element of array - why solution works in one direction and not the other

I like to know why the second solution works, but the first one, which has chained methods, doesn't.

This chained method doesn't work:

nopers = [5, 6, 7, 8, 9]

class Array
  define_method(:trimy) do
    self.shift().pop()
  end
end

      

When I test it, nopers.trimy (), it throws an undefined error. "pop" method for 1: Fixnum, in "block in" and only executes the .pop () method, removing 5.

But this version works:

yuppers = [1, 2, 3, 4, 5, 6]

class Array
  define_method(:trim) do
    self.shift()
    self.pop()
  end
end

yuppers.trim()

      

When I check this, yuppers gives me: [2, 3, 4, 5]

+3


source to share


2 answers


This is due to the fact that both shift

and pop

return the deleted value:

[1, 2, 3].pop   # => returns 3
[1, 2, 3].shift # => returns 1

      



So when you string them together, you are calling #pop

from the result #shift

, which is Integer

, which is not permitted.

+6


source


I would say that:

yuppers[1..-2]

      



is the simplest solution

+4


source







All Articles