From 39c22303a64db5592a1df6ece3d775ce09ff463c Mon Sep 17 00:00:00 2001 From: Kasper Timm Hansen Date: Tue, 10 Apr 2018 21:39:35 +0200 Subject: Add Enumerable#index_with. In the app I'm working on I've wished that index_by had a buddy that would assign the hash value instead of the key multiple times. Enter index_with. Useful when building a hash from a static list of symbols. Before you'd do: ```ruby POST_ATTRIBUTES.map { |attr_name| [ attr_name, public_send(attr_name) ] }.to_h ``` But now that's a little clearer and faster with: ````ruby POST_ATTRIBUTES.index_with { |attr_name| public_send(attr_name) } ``` It's also useful when you have an enumerable that should be converted to a hash, but you don't want to muddle the code up with the overhead that it takes to create that hash. So before, that's: ```ruby WEEKDAYS.each_with_object(Hash.new) do |day, intervals| intervals[day] = [ Interval.all_day ] end ``` And now it's just: ```ruby WEEKDAYS.index_with([ Interval.all_day ]) ``` It's also nice to quickly get a hash with either nil, [], or {} as the value. --- activesupport/test/core_ext/enumerable_test.rb | 15 +++++++++++++++ 1 file changed, 15 insertions(+) (limited to 'activesupport/test/core_ext') diff --git a/activesupport/test/core_ext/enumerable_test.rb b/activesupport/test/core_ext/enumerable_test.rb index 8d71320931..b63464a36a 100644 --- a/activesupport/test/core_ext/enumerable_test.rb +++ b/activesupport/test/core_ext/enumerable_test.rb @@ -179,6 +179,21 @@ class EnumerableTests < ActiveSupport::TestCase payments.index_by.each(&:price)) end + def test_index_with + payments = GenericEnumerable.new([ Payment.new(5), Payment.new(15), Payment.new(10) ]) + + assert_equal({ Payment.new(5) => 5, Payment.new(15) => 15, Payment.new(10) => 10 }, payments.index_with(&:price)) + + assert_equal({ title: nil, body: nil }, %i( title body ).index_with(nil)) + assert_equal({ title: [], body: [] }, %i( title body ).index_with([])) + assert_equal({ title: {}, body: {} }, %i( title body ).index_with({})) + + assert_equal Enumerator, payments.index_with.class + assert_nil payments.index_with.size + assert_equal 42, (1..42).index_with.size + assert_equal({ Payment.new(5) => 5, Payment.new(15) => 15, Payment.new(10) => 10 }, payments.index_with.each(&:price)) + end + def test_many assert_equal false, GenericEnumerable.new([]).many? assert_equal false, GenericEnumerable.new([ 1 ]).many? -- cgit v1.2.3