Removing the first and last element of an array on the same line?

How can I remove the first and last item on the same line in a smart way?

I tried:

names = %w[Go Go Go Power Rangers Go]
names.shift.pop

It can not be, because, I think, two shiftand popreturn a value, the remote, which is then transmitted to the next function, causing an error.

I also tried to do this work with delete_at, but it does not allow an array parameter, and therefore I do not get any more effort to make it a single layer.

Any ideas?

Note. I value minimalism

+3
source share
4 answers

You can use names = names[1..-2], but you should not. Just use names.pop; names.shiftand do it.

+3
source
_, *names, _ = %w[Go Go Go Power Rangers Go]
names #=> ["Go", "Go", "Power", "Rangers"]

, names, :

names = %w[Go Go Go Power Rangers Go]
_, *names, _ = names
names #=> ["Go", "Go", "Power", "Rangers"]
+5

?

names.slice!(1..-2)

, , , :

names.pop
names.shift
0

:

 _, *names, _ = names

, ?

In addition, I would use another variable (functional style)

_, *new_names, _ = names

Edit: Sorry, I realized that @sawa has already submitted this solution.

0
source

All Articles