Skip to content

Instantly share code, notes, and snippets.

@andersr
Created October 13, 2013 15:06
Show Gist options
  • Save andersr/6963340 to your computer and use it in GitHub Desktop.
Save andersr/6963340 to your computer and use it in GitHub Desktop.
# Create a method, apple_picker, that will pick all the apples out of an array. Implement it with collect and then implement it with select. Write a sentence about how select differs from collect.
fruits = ["orange", "banana", "apple", "orange", "apple", "banana", "orange", "apple"]
#with collect
def apple_picker_collect(array)
array.collect do |array_element|
array_element if array_element == "apple"
end
end
puts apple_picker_collect(fruits).compact
puts #add a space between the two methods
#with select
def apple_picker_select(array)
array.select do |array_element|
array_element if array_element == "apple"
end
end
puts apple_picker_select(fruits)
# The difference between the collect and select methods:
# Collect returns a new array containing everything in the original block but modified as per the collect block, so in the above it was necessary to use compact to remove all the fruits which returned nil.
# Select returns only that which returned true as per the select block, which made the compact call unnecessary.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment