【发布时间】:2019-08-08 02:06:16
【问题描述】:
鉴于这样的事情:
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
【问题讨论】:
-
无耻插件:我已经构建了 gem
iteraptor来服务于这个目的。 -
只需点击“编辑”按钮。您可以在这样做后删除您的评论,我也会这样做。
标签: ruby algorithm recursion hash