Added Enumerable#pluck to wrap the common pattern of collect(&:method) *DHH*

This commit is contained in:
David Heinemeier Hansson 2011-12-02 13:00:03 +01:00
parent 76a3ec7f6e
commit 4d20de8a50
3 changed files with 19 additions and 3 deletions

View File

@ -1,5 +1,7 @@
## Rails 3.2.0 (unreleased) ##
* 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.

View File

@ -63,6 +63,13 @@ module Enumerable
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" ]
def pluck(method)
collect { |element| element.send(method) }
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 File

@ -126,4 +126,11 @@ class EnumerableTests < Test::Unit::TestCase
assert_equal true, GenericEnumerable.new([ 1 ]).exclude?(2)
assert_equal false, GenericEnumerable.new([ 1 ]).exclude?(1)
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