Iterate over a deeply nested level of hashes in Ruby

后端 未结 8 1761
眼角桃花
眼角桃花 2020-12-05 00:13

So I have a hash, and for each level of the hash, I want to store its key and value. The problem is, a value can be another hash array. Furthermore, that hash can contain ke

8条回答
  •  囚心锁ツ
    2020-12-05 00:31

    If you want to recursively edit the hash, you could do something like this:

    # Iterates over a Hash recursively
    def each_recursive(parent, &block)
      parent.each do |path, value|
        if value.kind_of? Hash
          each_recursive parent, &block
        elsif value.is_a? Array
          # @TODo something different for Array?
        else
          yield(parent, path, container_or_field)
        end
      end
    end
    

    And you can do something like:

    hash = {...}
    each_recursive(hash) do |parent, path, value|
      parent[path] = value.uppercase
    end
    

提交回复
热议问题