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

Kevin Zheng
Kevin Zheng
670 Points

why is the output still containing all the variable?

hash={"name"=>"jason","location"=>"Treehouse"}
#hash.keep_if { |key, value|  key=="name"}
#hash.reject{|key,value| key=="name"}
#hash={"name"=>"jason","location"=>"Treehouse"}
hash.select{|key,value| key=="name"}
puts hash

why is the output like this : {"name"=>"jason", "location"=>"Treehouse"} ?

I think it should be just {"name"=>"jason"}

1 Answer

Hi Kevin,

select doesn't modify the hash but returns a new hash instead. So if you want to print the result then you either need to save it in a variable and print that or print the return result directly.

puts hash.select{|key,value| key=="name"}

On the other hand, select! will modify the hash and it works the same as keep_if except that select! will return nil if the hash wasn't changed.