Module: Enumerable
- Defined in:
- lib/enumerate_hash_values/core_extensions/enumerable.rb
Overview
:nodoc:
Instance Method Summary collapse
-
#collect_to_hash(hash_class = Hash) ⇒ Object
(also: #map_to_hash)
Wraps the common pattern of doing:.
-
#collect_to_hash_values(hash_class = Hash) ⇒ Object
(also: #map_to_hash_values)
Similar to
collect_to_hash, but the specified block only needs to return the hash value for each enumerated item.
Instance Method Details
#collect_to_hash(hash_class = Hash) ⇒ Object Also known as: map_to_hash
Wraps the common pattern of doing:
enumerable.inject({}) do |hash, item|
some_key = item.key
some_value = item.value
hash[some_key] = some_value
hash
end
Using collect_to_hash instead:
enumerable.collect_to_hash do |item|
some_key = item.key
some_value = item.value
[some_key, some_value]
end
Examples:
(1..3).collect_to_hash { |number| [number, number * 10] } # => { 1 => 10, 2 = > 20, 3 => 30 }
%w(a b c).map_to_hash { |letter| [letter, letter[0]] } # => { 'a' => 97, 'b' => 98, 'c' => 99 }
Aliases map_to_hash
26 27 28 29 30 31 32 33 34 |
# File 'lib/enumerate_hash_values/core_extensions/enumerable.rb', line 26 def collect_to_hash(hash_class = Hash) raise ArguementError.new("#{hash_class} is not a Hash") unless hash_class.ancestors.include?(Hash) inject(hash_class.new) do |hash, item| key, value = yield(item) hash[key] = value hash end end |
#collect_to_hash_values(hash_class = Hash) ⇒ Object Also known as: map_to_hash_values
Similar to collect_to_hash, but the specified block only needs to return the hash value for each enumerated item. The items themselves will serve as the hash keys.
(1..3).collect_to_hash_values { |number| number * 10 } # => { 1 => 10, 2 = > 20, 3 => 30 }
%w(a b c).map_to_hash_values(&:to_sym) # => { 'a' => :a, 'b' => :b, 'c' => :c }
Aliases map_to_hash_values
45 46 47 |
# File 'lib/enumerate_hash_values/core_extensions/enumerable.rb', line 45 def collect_to_hash_values(hash_class = Hash) collect_to_hash(hash_class) { |item| [item, yield(item)] } end |