Skip to content

Instantly share code, notes, and snippets.

@kv109
Created October 29, 2010 12:06
Show Gist options
  • Save kv109/653424 to your computer and use it in GitHub Desktop.
Save kv109/653424 to your computer and use it in GitHub Desktop.
Don't use each when you can use map
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