Module: Corefines::Hash::Recurse

Defined in:
lib/corefines/hash.rb

Instance Method Summary collapse

Instance Method Details

#recurse {|Hash| ... } ⇒ Hash

Transforms this hash and each of its sub-hashes recursively using the given block.

It does not mutate the hash if the given block is pure (i.e. does not modify given hashes, but returns new ones).

Examples:

hash = {"a" => 1, "b" => {"c" => {"e" => 5}, "d" => 4}}

hash.recurse { |h| h.symbolize_keys }  # => {a: 1, b: {c: {e: 5}, d: 4}}
hash  # => {"a" => 1, "b" => {"c" => {"e" => 5}, "d" => 4}}

hash.recurse { |h| h.symbolize_keys! }  # => {a: 1, b: {c: {e: 5}, d: 4}}
hash  # => {a: 1, b: {c: {e: 5}, d: 4}}

Yields:

  • (Hash)

    gives this hash and every sub-hash (recursively). The return value replaces the old value.

Returns:

  • (Hash)

    a result of applying block to this hash and each of its sub-hashes (recursively).


194
195
196
197
198
199
200
201
202
203
# File 'lib/corefines/hash.rb', line 194

module Recurse
  refine ::Hash do
    def recurse(&block)
      h = yield(self)
      h.each do |key, value|
        h[key] = value.recurse(&block) if value.is_a? ::Hash
      end
    end
  end
end