Created
July 17, 2012 18:53
-
-
Save mtheoryx/3131260 to your computer and use it in GitHub Desktop.
Search within an array of hashes by value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Say you have an array of hashes. They keys can be strings or symbols, | |
| # Ruby doesn't care much in this instance. | |
| # And say you want to do a search based on the value of one of those hash keys. | |
| # First, let's make a new array of hashes. | |
| haystack = Array.new | |
| haystack << {:title => "Privacy Status", :id => "sakai.privacy"} | |
| haystack << {:title => "Worksite Information", :id => "sakai.iframe.site"} | |
| haystack << {:title => "Site Setup", :id => "sakai.siteinfo"} | |
| # Now let's try to find one of these array elements | |
| # We'll pick an arbitrary criteria. I'm going to look | |
| # for an :id with a specified value. | |
| # We can use the Enumerable#select method! | |
| result = haystack.select {|h| h[:id] == "sakai.siteinfo"} | |
| # We can see that the result is the entire array element for that match | |
| p result | |
| #=> [{:title=>"Site Setup", :id=>"sakai.siteinfo"}] | |
| p result.empty? | |
| #=> false | |
| # And just to verify, what happends when you don't find a match: | |
| wrong_result = haystack.select {|h| h[:id] == "wrong.tool.id"} | |
| p wrong_result | |
| #=> [] | |
| p wrong_result.empty? | |
| #=> true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment