6

I'm working my way through Learning Ruby the Hard Way online; I've just finished the 26th exercise which was a "test" whereby you fixed someone's broken code.

My problem came with using an argument with the pop method. I'm familiar with the basics but the correct answer meant changing the argument from "-1" to "1", and I'm not sure what it means, exactly.

The line in question is:

def puts_last_word(words)
    word = words.pop(1)
    puts word
end

I assume it pops the second element from the array but I would like confirmation or help, whichever is appropriate.

1
  • 1
    Don't assume, use ri Array.pop. Commented Dec 6, 2011 at 23:49

2 Answers 2

4

The best confirmation can be had in the documentation of Array#pop: http://rubydoc.info/stdlib/core/1.9.3/Array:pop

According to that, the argument specifies how many elements, counting from the back of the array, to remove.

The only difference between pop() and pop(1) is that the former will return a single element (the deleted one), while the latter will return an array with a single element (again, the deleted one).

Edit: I suppose the reason the test used -1 is to teach you about the difference between array access with #[], where -1 would mean the last element, and methods like pop, that expect an amount, not a position, as their argument.

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

1 Comment

Excellent answer, completely makes sense. It was the first time I'd seen something like that, so I was confused. (Thanks for the link to the Docs too, hopefully I'll cut out the stoooopid questions now.)
2

The argument specifies how many items to pop. If you specify an argument it returns an array whereas not specifying an argument returns just the element:

ruby-1.8.7-p352 :006 > a = [1,2,3]
=> [1, 2, 3] 
ruby-1.8.7-p352 :007 > a.pop(1)
=> [3] 
ruby-1.8.7-p352 :008 > a = [4,5,6]
=> [4, 5, 6] 
ruby-1.8.7-p352 :009 > a.pop(2)
=> [5, 6]
ruby-1.8.7-p352 :010 > a.pop
=> 4 

1 Comment

Thanks also for the help! Really appreciate it!

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.