Iterate over a deeply nested level of hashes in Ruby

后端 未结 8 1736
眼角桃花
眼角桃花 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:37

    If I understand the goal, then you should be able to pass in the parent to your save method. For the top level, it will be nil. The following shows the idea where puts is used as a place holder for the "save".

    def save_pair(parent, myHash)
      myHash.each {|key, value|
        value.is_a?(Hash) ? save_pair(key, value) :
                puts("parent=#{parent.nil? ? 'none':parent}, (#{key}, #{value})")
      }
    end
    

    Here is an example call to it:

    hash = Hash.new
    hash["key1"] = "value1"
    hash["key2"] = "value2"
    hash["key3"] = Hash.new
    hash["key3"]["key4"] = "value4"
    hash["key3"]["key5"] = "value5"
    hash["key6"] = Hash.new
    hash["key6"]["key7"] = "value7"
    hash["key6"]["key8"] = Hash.new
    hash["key6"]["key8"]["key9"] = "value9"
    
    save_pair(nil, hash)
    

提交回复
热议问题