Skip to content
Browse files

Added Enumerable#pluck to wrap the common pattern of collect(&:method…

…) *DHH*
  • Loading branch information...
1 parent 76a3ec7 commit 4d20de8a50d889a09e6f5642984775fe796ca943 @dhh dhh committed
View
6 activesupport/CHANGELOG.md
@@ -1,7 +1,9 @@
## Rails 3.2.0 (unreleased) ##
-* Module#synchronize is deprecated with no replacement. Please use `monitor`
- from ruby's standard library.
+* Added Enumerable#pluck to wrap the common pattern of collect(&:method) *DHH*
+
+* Module#synchronize is deprecated with no replacement. Please use `monitor`
+ from ruby's standard library.
* (Date|DateTime|Time)#beginning_of_week accept an optional argument to
be able to set the day at which weeks are assumed to start.
View
7 activesupport/lib/active_support/core_ext/enumerable.rb
@@ -63,6 +63,13 @@ def sum(identity = 0, &block)
end
end
+ # Plucks the value of the passed method for each element and returns the result as an array. Example:
+ #
+ # people.pluck(:name) # => [ "David Heinemeier Hansson", "Jamie Heinemeier Hansson" ]
@tenderlove Ruby on Rails member

people.map(&:name) # => [ "David Heinemeier Hansson", "Jamie Heinemeier Hansson" ]

@dimko
dimko added a note
                           user     system      total        real
people.pluck(:name)    0.250000   0.000000   0.250000   (0.269815)
people.map(&:name)     0.140000   0.000000   0.140000   (0.148966)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+ def pluck(method)
+ collect { |element| element.send(method) }
@jonleighton Ruby on Rails member

How about using public_send on 1.9?

@josevalim Ruby on Rails member

Could also be collect(&method)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+ end
+
# Iterates over a collection, passing the current element *and* the
# +memo+ to the block. Handy for building up hashes or
# reducing collections down to one object. Examples:
View
9 activesupport/test/core_ext/enumerable_test.rb
@@ -126,4 +126,11 @@ def test_exclude?
assert_equal true, GenericEnumerable.new([ 1 ]).exclude?(2)
assert_equal false, GenericEnumerable.new([ 1 ]).exclude?(1)
end
-end
+
+ def test_pluck_single_method
+ person = Struct.new(:name)
+ people = [ person.new("David"), person.new("Jamie") ]
+
+ assert_equal [ "David", "Jamie" ], people.pluck(:name)
+ end
+end

0 comments on commit 4d20de8

Please sign in to comment.
Something went wrong with that request. Please try again.