给定这样的东西:
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_at
和 updated_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
最佳答案
据我了解,您对散列的了解嘿
是它由嵌套的散列组成。
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
的更新值。
关于Ruby 嵌套哈希合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55208935/