Created
October 29, 2010 12:06
-
-
Save kv109/653424 to your computer and use it in GitHub Desktop.
Don't use each when you can use map
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
class Argument | |
attr_reader :weight | |
def initialize(weight) | |
@weight = weight | |
end | |
end | |
arguments = [] | |
4.times { |i| arguments << Argument.new(i) } | |
#the long way to get all weights: | |
weights = [] | |
arguments.each do |arg| | |
weights << arg.weight | |
end | |
weights #=> [0, 1, 2, 3] | |
#short way | |
weights = arguments.map(&:weight) | |
weights #=> [0, 1, 2, 3] | |
#why don't get the sum of all weights? | |
sum = arguments.map(&:weight).inject{ |sum, n| sum + n } | |
sum #=> 6 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment