Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


4,506 Points


Does Hash.shift always return an array with the first ("index zero") key-value pair? I'm just confused because I thought one of the main differences between hashes and arrays is that hashes are not searchable by index? Do the items in a hash remain in a specified order? Thanks!

1 Answer

The best thing to do when you have a question like this is to open irb and have a play. That's what I did:

h = {one: 1, two: 2, three: 3}
=> [:one, 1]
=> {:two => 2, :three => 3}

So, the shift method is destructive. It returns an array of the first key/value pair of the hash and also 'mutates' the hash.

The other way to find this out is to google "ruby hash shift" - the top result is the ruby docs for hash methods - find the 'shift' method in the left hand box and click on it. That jumps to the shift method down the page (here). It's easy to see what the shift method does there. It's not always as clear as that, but in this case it's easy to instantly see what it does.

4,506 Points

Thanks! My question was not actually about what the shift function does. I do understand that, but the fact that this function works is confusing to me, because I thought that hashes, dictionaries, etc, are not indexed?