Module: Corefines::Hash::FlatMap

Defined in:
lib/corefines/hash.rb

Instance Method Summary collapse

Instance Method Details

#flat_map {|key, value| ... } ⇒ Hash

Returns a new hash with the merged results of running the block once for every entry in self.

Examples:

hash = { a: 1, b: 2, c: 3 }
hash.flat_map { |k, v| {k => v * 2, k.upcase => v} if v % 2 == 1 }
# => { a: 2, A: 1, c: 6, C: 3 }
hash.flat_map { |k, v| [[k, v * 2], [k.upcase => v]] if v % 2 == 1 }
# => { a: 2, A: 1, c: 6, C: 3 }

Yields:

  • (key, value)

    gives every key-value pair to the block.

Yield Returns:

  • (#to_h, Array, nil)

    an object that will be interpreted as a Hash and merged into the result, or nil to omit this key-value.


88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/corefines/hash.rb', line 88

module FlatMap
  refine ::Hash do
    def flat_map
      each_with_object({}) do |(key, value), hash|
        yielded = yield(key, value)

        if yielded.is_a? ::Hash
          hash.merge!(yielded)
        elsif yielded.is_a? ::Array
          # Array#to_h exists since Ruby 2.1.
          yielded.each do |pair|
            hash.store(*pair)
          end
        elsif yielded
          hash.merge!(yielded.to_h)
        end
      end
    end
  end
end