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

Ruby

Help with Hashes

Hi - I'm a complete novice when it comes to programming and also Ruby so apologies in advance if what I'm asking is super easy :-)

I'm trying to iterate through my hash and moving items into arrays if they contain a certain string. Any help as to why it doesn't seem to do any matching would be great.

My code is:

firsthash = {'film' => ["Shawshank redemption","Paul","Shaun of the dead"]} match = [] nonmatch = [] firsthash.each do |item| if item.include?('au') match.push(item) else nonmatch.push(item) end end

puts match puts nonmatch

2 Answers

Stone Preston
Stone Preston
42,016 Points

your for each loop is iterating over the items in the hash, not the ones in the array that is nested in the hash. it loops over the items in the hash, instead of going over each item in the hash, and then each item of that item and checking if it includes something. You need to add a for each loop inside of your first one

firsthash.each do |hash_item| 

    hash_item.each do |array_item|

           #code to check if it includes the string goes here and pushing goes here as well

    end

end

Doh!! of course! I was thinking that the each_value was picking the array values. I've changed the code and it works perfectly.

Thank you so much for your help :-)