diff options
author | Kasper Timm Hansen <kaspth@gmail.com> | 2018-04-10 21:39:35 +0200 |
---|---|---|
committer | Kasper Timm Hansen <kaspth@gmail.com> | 2018-05-21 17:44:54 +0200 |
commit | 39c22303a64db5592a1df6ece3d775ce09ff463c (patch) | |
tree | 92adb8733656bee8c933c36cf919fc5ebf779f48 /activesupport/test/core_ext | |
parent | ba07b5fc12a740d41d288bea6347f15f4948483c (diff) | |
download | rails-39c22303a64db5592a1df6ece3d775ce09ff463c.tar.gz rails-39c22303a64db5592a1df6ece3d775ce09ff463c.tar.bz2 rails-39c22303a64db5592a1df6ece3d775ce09ff463c.zip |
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.
Diffstat (limited to 'activesupport/test/core_ext')
-rw-r--r-- | activesupport/test/core_ext/enumerable_test.rb | 15 |
1 files changed, 15 insertions, 0 deletions
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? |