Ruby Nested Hash Merge

问题描述 投票:0回答:1

鉴于这样的事情:

hey = {
  some_key: {
      type: :object,
      properties: {
        id: { type: :string, example: '123', description: 'Id' },
        created_at: { type: :string, example: '2019-02-14 14:13:55'},
        updated_at: { type: :string, example: '2019-02-14 14:13:55'},
        type: { type: :string, example: 'something', description: 'Resource type' },
        token: { type: :string, example: 'token', description: 'Some description of token' }
      }
    }
}

我想通过所有密钥,直到找到一个名为properties,然后改变其内容,使得密钥成为description密钥的值,如果它不在其嵌套散列中退出。

所以对于上面的例子,哈希最终会像这样:

hey = {
  some_key: {
      type: :object,
      properties: {
        id: { type: :string, example: '123', description: 'Id' },
        created_at: { type: :string, example: '2019-02-14 14:13:55', description: 'Created At'},
        updated_at: { type: :string, example: '2019-02-14 14:13:55', description: 'Updated At'},
        type: { type: :string, example: 'something', description: 'Resource type' },
        token: { type: :string, example: 'token', description: 'Some description of token' }
      }
    }
}

created_atupdated_at没有描述。

如果tokenproperties属性,它也应该处理。

我提出了一个有效的解决方案,但我真的很好奇我如何改进它?

我的解答如下:

def add_descriptions(hash)
  return unless hash.is_a?(Hash)
  hash.each_pair do |key, value|
    if key == :properties
      value.each do |attr, props|
        if props[:description].nil?
          props.merge!(description: attr.to_s)
        end
      end
    end
    add_descriptions(value)
  end
end
ruby algorithm recursion hash
1个回答
1
投票

据我所知,哈希hey的所有知识都是由嵌套的哈希组成。

def recurse(h)
  if h.key?(:properties)
    h[:properties].each do |k,g|
      g[:description] = k.to_s.split('_').map(&:capitalize).join(' ') unless
        g.key?(:description)
    end
  else
    h.find { |k,obj| recurse(obj) if obj.is_a?(Hash) }
  end
end

recurse hey
  #=> {:id=>{:type=>:string, :example=>"123", :description=>"Id"},
  #    :created_at=>{:type=>:string, :example=>"2019-02-14 14:13:55",
  #      :description=>"Created At"},
  #    :updated_at=>{:type=>:string, :example=>"2019-02-14 14:13:55",
  #    :description=>"Updated At"},
  #    :type=>{:type=>:string, :example=>"something",
  #      :description=>"Resource type"},
  #    :token=>{:type=>:string, :example=>"token",
  #      :description=>"Some description of token"}} 

返回值是hey的更新值。

© www.soinside.com 2019 - 2024. All rights reserved.