Last active
August 29, 2015 13:59
-
-
Save dannguyen/10883501 to your computer and use it in GitHub Desktop.
Ruby enumerable fun sugar: http://ruby-doc.org/core-1.9.3/Enumerable.html
This file contains 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
stores.each do |store| | |
if country == store[:name] | |
store_id = store[:id] | |
break | |
end | |
end | |
# http://ruby-doc.org/core-1.9.3/Enumerable.html | |
### With #select | |
s = stores.select{ |store| country == store[:id] }.first # select returns an array | |
store_id = s[:id] | |
### With #find | |
s = stores.find{ |store| country == store[:id] } | |
store_id = s[:id] | |
### with a conditional just in case no elements match | |
s = stores.find{ |store| country == store[:id] } | |
store_id = s[:id] if s | |
### with really lazy and sometimes easy-to-screwup assignment via-if | |
if( s = stores.find{ |store| country == store[:id] } ) | |
store_id = s[:id] | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment