Created
September 30, 2013 20:53
-
-
Save davidbella/6770100 to your computer and use it in GitHub Desktop.
Ruby: Holiday Supplies and Apple Picker - working with hashes and select/collect
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
# Using collect, we have to explicitly set the return value | |
# And then to clean up - use compact to eliminate nils | |
def apple_picker(foods) | |
apples = (foods.collect do |food| | |
if food == "apple" | |
food | |
end | |
end).compact | |
end | |
p apple_picker(["apple", "orange", "apple"]) | |
# With select, we are given the value if our conditional returns true | |
# No need to clean up nil since it isn't even returned | |
def apple_picker(foods) | |
apples = foods.select do |food| | |
food == "apple" | |
end | |
end | |
p apple_picker(["apple", "orange", "apple"]) |
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
holiday_supplies = { | |
:winter => { | |
:christmas => ["Lights", "Wreath"], | |
:new_years => ["Party Hats", "Alcohol"] | |
}, | |
:summer => { | |
:forth_of_july => ["Fireworks", "BBQ"] | |
}, | |
:fall => { | |
:thanksgiving => ["Turkey"], | |
:halloween => ["Costumes", "Candy"] | |
}, | |
:spring => { | |
:memorial_day => ["BBQ", "Parade"] | |
} | |
} | |
# 1. Access the second supply for forth_of_july | |
p holiday_supplies[:summer][:forth_of_july][1] | |
# 5. All supplies from all winter holidays | |
list = (holiday_supplies[:winter].collect do |holiday, supply_list| | |
supply_list.collect do |item| | |
item | |
end | |
end).flatten | |
p list | |
# 6. All supplies for each holiday and season | |
holiday_supplies.each do |season, holiday_hash| | |
puts season | |
holiday_hash.each do |holiday, supply_list| | |
puts " #{holiday}" | |
supply_list.each do |supply| | |
puts " #{supply}" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment