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