aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport
diff options
context:
space:
mode:
Diffstat (limited to 'activesupport')
-rw-r--r--activesupport/CHANGELOG.md7
-rw-r--r--activesupport/lib/active_support/core_ext/enumerable.rb8
-rw-r--r--activesupport/test/core_ext/enumerable_test.rb5
3 files changed, 20 insertions, 0 deletions
diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md
index 2fac308d2e..e77ebcb2f2 100644
--- a/activesupport/CHANGELOG.md
+++ b/activesupport/CHANGELOG.md
@@ -1,3 +1,10 @@
+* Add `Enumerable#pluck` to get the same values from arrays as from ActiveRecord
+ associations.
+
+ Fixes #20339.
+
+ *Kevin Deisz*
+
* Add a bang version to `ActiveSupport::OrderedOptions` get methods which will raise
an `KeyError` if the value is `.blank?`
diff --git a/activesupport/lib/active_support/core_ext/enumerable.rb b/activesupport/lib/active_support/core_ext/enumerable.rb
index 7a893292b3..d28f26260e 100644
--- a/activesupport/lib/active_support/core_ext/enumerable.rb
+++ b/activesupport/lib/active_support/core_ext/enumerable.rb
@@ -71,6 +71,14 @@ module Enumerable
def without(*elements)
reject { |element| elements.include?(element) }
end
+
+ # Convert an enumerable to an array based on the given key.
+ #
+ # [{ name: "David" }, { name: "Rafael" }, { name: "Aaron" }].pluck(:name)
+ # => ["David", "Rafael", "Aaron"]
+ def pluck(key)
+ map { |element| element[key] }
+ end
end
class Range #:nodoc:
diff --git a/activesupport/test/core_ext/enumerable_test.rb b/activesupport/test/core_ext/enumerable_test.rb
index e5d8ae7882..21743cdea5 100644
--- a/activesupport/test/core_ext/enumerable_test.rb
+++ b/activesupport/test/core_ext/enumerable_test.rb
@@ -110,4 +110,9 @@ class EnumerableTests < ActiveSupport::TestCase
assert_equal [1, 2, 4], (1..5).to_set.without(3, 5)
assert_equal({foo: 1, baz: 3}, {foo: 1, bar: 2, baz: 3}.without(:bar))
end
+
+ def test_pluck
+ payments = GenericEnumerable.new([ Payment.new(5), Payment.new(15), Payment.new(10) ])
+ assert_equal [5, 15, 10], payments.pluck(:price)
+ end
end