I's like to know why the second solution works but the first one, which has chained methods, doesn't work.
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 gives an undefined error message. "method 'pop' for 1:Fixnum, in 'block in '" and only executes the .pop() method, removing the 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 test it, yuppers gives me: [2, 3, 4, 5]
To remove the first and last elements from an array, call the shift() and pop() methods on the Array. The shift method removes the first and the pop method removes the last element from an array. Both methods return the removed elements.
You can use Array. delete_at(0) method which will delete first element.
The pop() function in Ruby is used to pop or remove the last element of the given array and returns the removed elements.
I would say that:
yuppers[1..-2]
is the most simple solution
This is because both shift
and pop
return the value that is removed:
[1, 2, 3].pop # => returns 3
[1, 2, 3].shift # => returns 1
So when you chain them together you're calling #pop
on the result of #shift
, which is an Integer
which isn't allowed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With