Skip to content

Instantly share code, notes, and snippets.

@rayning0
Created September 30, 2013 22:08
Show Gist options
  • Select an option

  • Save rayning0/6771026 to your computer and use it in GitHub Desktop.

Select an option

Save rayning0/6771026 to your computer and use it in GitHub Desktop.
Apple Picker and Holiday Suppliers
def apple_picker(a)
puts "Using 'collect':"
p a.collect{|x| x if x == 'apple'}.compact
puts "Using 'select':"
p a.select{|x| x == 'apple'}
end
apple_picker(["apple", "orange", "apple"]) #=> ["apple", "apple"]
puts "'Collect' returns array with values returned by block, but it has same"
puts "no. of values as original array. Any values not returned by block are nil."
puts "I needed 'compact' method to eliminate 'nils.'"
puts
puts "'Select' returns new array containing all elements of ary for which"
puts "the given block returns a true value. No 'nils' or need for 'compact.'"
holiday_supplies = {
:winter => {
:christmas => ["Lights", "Wreath"],
:new_years => ["Party Hats"]
},
:summer => {
:forth_of_july => ["Fireworks", "BBQ"]
},
:fall => {
:thanksgiving => ["Turkey"]
},
:spring => {
:memorial_day => ["BBQ"]
}
}
#1
puts holiday_supplies[:summer][:forth_of_july][1]
puts
#2
p holiday_supplies[:winter][:christmas] << 'Stars'
puts
#3
p holiday_supplies[:spring][:memorial_day] << 'Steak'
puts
#4
p holiday_supplies[:spring][:valentines_day] = ['Hearts']
puts
#5
def winter_suppliers(hs)
wsupplies = hs[:winter].collect do |holiday, supply|
supply
end
wsupplies.flatten! # flattens nested array: [["Lights", "Wreath"], ["Party Hats"]]
end
p winter_suppliers(holiday_supplies)
puts
#6
def print_supplies(hs)
hs.each do |season, holidays|
puts "#{season.capitalize}:"
holidays.each do |holiday, supply|
print " #{holiday.capitalize}: "
supply.each_with_index do |s, i|
print "#{s}"
print " and " if i < supply.size - 1
end
puts
end
end
end
print_supplies(holiday_supplies)
puts
#7
def holidays_with_bbqs(hs)
h = []
hs.each_value do |holidays|
holidays.each do |holiday, supply|
h << holiday if supply.include?('BBQ')
end
end
h
end
p holidays_with_bbqs(holiday_supplies)
# Output
=begin
Using 'collect':
["apple", "apple"]
Using 'select':
["apple", "apple"]
'Collect' returns array with values returned by block, but it has same
no. of values as original array. Any values not returned by block are nil.
I needed 'compact' method to eliminate 'nils.'
'Select' returns new array containing all elements of ary for which
the given block returns a true value. No 'nils' or need for 'compact.'
BBQ
["Lights", "Wreath", "Stars"]
["BBQ", "Steak"]
["Hearts"]
["Lights", "Wreath", "Stars", "Party Hats"]
Winter:
Christmas: Lights and Wreath and Stars
New_years: Party Hats
Summer:
Forth_of_july: Fireworks and BBQ
Fall:
Thanksgiving: Turkey
Spring:
Memorial_day: BBQ and Steak
Valentines_day: Hearts
[:forth_of_july, :memorial_day]
=end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment