Files changed (3) hide show
  1. checksums.yaml +7 -0
  2. data/lib/reduce_to_hash.rb +38 -0
  3. metadata +44 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: fdac832c4bae62d2732a1a3723773da372c8a38d3bf3bb37844db05d21fd2be8
4
+ data.tar.gz: d41a72afb28eafbd1b23f30fe670fb81fa9d4d0e4e08bfa9b098c59eafe39c6c
5
+ SHA512:
6
+ metadata.gz: e4c3bfd17697f5b8cb40955be5ec36cd89d82072860a5f2115bceeff50051a037705ff5f17d6cfc686b9cb6d7b35fc8651610ae97f1713b2f0688ed825521c4e
7
+ data.tar.gz: ad61ffbe7dd34e2032debc8c924e4bc7e585ad445b438596ca9f2eda94ac05586e4bd6d8696e9ca377a1a8038485d854bc73d49c552b1c876ecbbc3712de1aec
data/lib/reduce_to_hash.rb ADDED
@@ -0,0 +1,38 @@
1
+ class Array
2
+ def reduce_to_hash(sym_or_hash = nil, &block)
3
+ raise ArgumentError.new('Either block or symbol(s) required') if block.nil? and sym_or_hash.nil?
4
+ raise ArgumentError.new('Block and symbol(s) cannot be used together') unless block.nil? or sym_or_hash.nil?
5
+
6
+ if block
7
+ self.reduce({}) do |memo, item|
8
+ mapped = block.call(item)
9
+ if mapped.nil?
10
+ memo
11
+ else
12
+ memo.merge(mapped)
13
+ end
14
+ end
15
+
16
+ elsif sym_or_hash.respond_to? :keys
17
+ raise ArgumentError.new('Mapping hash must have single k=>v pair') if sym_or_hash.keys.length != 1
18
+
19
+ key = sym_or_hash.keys.first
20
+ val = sym_or_hash.values.first
21
+ self.reduce({}) { |memo, item| memo.merge({rth_extract(item, key) => rth_extract(item, val)}) }
22
+
23
+ else
24
+ self.reduce({}) { |memo, item| memo.merge({rth_extract(item, sym_or_hash) => item}) }
25
+
26
+ end
27
+ end
28
+
29
+ private
30
+
31
+ def rth_extract(item, key)
32
+ if item.is_a? Hash
33
+ item[key]
34
+ else
35
+ item.send(key)
36
+ end
37
+ end
38
+ end
metadata ADDED
@@ -0,0 +1,44 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: reduce_to_hash
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - smendola@gmail.com
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2020-01-13 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description:
14
+ email:
15
+ executables: []
16
+ extensions: []
17
+ extra_rdoc_files: []
18
+ files:
19
+ - lib/reduce_to_hash.rb
20
+ homepage:
21
+ licenses:
22
+ - MIT
23
+ metadata: {}
24
+ post_install_message:
25
+ rdoc_options: []
26
+ require_paths:
27
+ - lib
28
+ required_ruby_version: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: '0'
33
+ required_rubygems_version: !ruby/object:Gem::Requirement
34
+ requirements:
35
+ - - ">="
36
+ - !ruby/object:Gem::Version
37
+ version: '0'
38
+ requirements: []
39
+ rubyforge_project:
40
+ rubygems_version: 2.7.7
41
+ signing_key:
42
+ specification_version: 4
43
+ summary: Reduce an array to a hash that indexes the array
44
+ test_files: []