Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Remove first and last element of an Array - why the solution works one way & not the other

Tags:

arrays

ruby

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]

like image 250
Padawan Avatar asked May 16 '15 23:05

Padawan


People also ask

How do you remove the first and last element in an array?

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.

How do you remove the first element from an array in Ruby?

You can use Array. delete_at(0) method which will delete first element.

How do you remove the last element of an array in Ruby?

The pop() function in Ruby is used to pop or remove the last element of the given array and returns the removed elements.


2 Answers

I would say that:

yuppers[1..-2]

is the most simple solution

like image 98
lucianosousa Avatar answered Oct 05 '22 23:10

lucianosousa


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.

like image 36
Will Richardson Avatar answered Oct 06 '22 00:10

Will Richardson