diff options
-rw-r--r-- | activesupport/CHANGELOG.md | 2 | ||||
-rw-r--r-- | activesupport/lib/active_support/core_ext/enumerable.rb | 25 | ||||
-rw-r--r-- | activesupport/test/core_ext/enumerable_test.rb | 7 |
3 files changed, 20 insertions, 14 deletions
diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md index f23ee6e045..50c83478d1 100644 --- a/activesupport/CHANGELOG.md +++ b/activesupport/CHANGELOG.md @@ -7,8 +7,6 @@ * Add ActiveSupport::Cache::NullStore for use in development and testing. *Brian Durand* -* 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. diff --git a/activesupport/lib/active_support/core_ext/enumerable.rb b/activesupport/lib/active_support/core_ext/enumerable.rb index 3f13468e4d..c2e7cc80a1 100644 --- a/activesupport/lib/active_support/core_ext/enumerable.rb +++ b/activesupport/lib/active_support/core_ext/enumerable.rb @@ -26,12 +26,27 @@ module Enumerable end end - # Plucks the value of the passed method for each element and returns the result as an array. Example: + # 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: # - # people.pluck(:name) # => [ "David Heinemeier Hansson", "Jamie Heinemeier Hansson" ] - def pluck(method) - collect { |element| element.send(method) } - end + # %w(foo bar).each_with_object({}) { |str, hsh| hsh[str] = str.upcase } + # # => {'foo' => 'FOO', 'bar' => 'BAR'} + # + # *Note* that you can't use immutable objects like numbers, true or false as + # the memo. You would think the following returns 120, but since the memo is + # never changed, it does not. + # + # (1..5).each_with_object(1) { |value, memo| memo *= value } # => 1 + # + def each_with_object(memo) + return to_enum :each_with_object, memo unless block_given? + each do |element| + yield element, memo + end + memo + end unless [].respond_to?(:each_with_object) +>>>>>>> parent of 4d20de8... Added Enumerable#pluck to wrap the common pattern of collect(&:method) *DHH* # Convert an enumerable to a hash. Examples: # diff --git a/activesupport/test/core_ext/enumerable_test.rb b/activesupport/test/core_ext/enumerable_test.rb index 7c2aec3462..f10e6c82e4 100644 --- a/activesupport/test/core_ext/enumerable_test.rb +++ b/activesupport/test/core_ext/enumerable_test.rb @@ -117,11 +117,4 @@ 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 |