Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Ruby

lindseyk
lindseyk
4,506 Points

Hash.shift()

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}
h.shift
=> [:one, 1]
h
=> {: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.

lindseyk
lindseyk
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?