5

My code currently looks like this

numbers = [1, 2, 3, 4, 5]

def pop_three
  pop = []
  3.times { pop << numbers.pop }
  return pop
end

Is there any way to do what's inside the pop_three method in one line?

I basically want to do something like numbers.slice(0, 3) but deleting the array items that are in the slice.

Uhm...hrmmm, I think I just realized I can try slice!

0

2 Answers 2

8

Yes

numbers.pop(3)

Or

numbers.shift(3)

If you want this other side.

Sign up to request clarification or add additional context in comments.

5 Comments

Interesting, wonder when they added that. The docs I have don't mention any parameters.
you could have added the shift one to pass the limit ;-)
@brand I didn't read the doc. Just tried. Sometimes Ruby act as expected ;-)
Array#pop|shift accepts parameters since Ruby 1.8.7. See for instance RubySpec ( github.com/rubyspec/rubyspec/blob/master/core/array/… ).
Here's the updated link since these specs are now under the github/ruby repo (github.com/ruby/ruby/blob/master/spec/ruby/core/array/…) @Marc-AndréLafortune
0

what about numbers.slice(x.size-3,3).reverse

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.