Ruby嵌套哈希合并

时间:2019-03-17 15:53:45

标签: ruby algorithm recursion hash

给出类似这样的内容:

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没有描述。

它还应该处理例如token是否具有properties属性。

我想出了一个可行的解决方案,但是我真的很好奇如何改进它?

我的解决方案如下:

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

1 个答案:

答案 0 :(得分: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的更新值。