Ruby 嵌套哈希合并

标签 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

最佳答案

据我了解,您对散列的了解是它由嵌套的散列组成。

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/

相关文章:

ruby-on-rails - 如何计算循环次数

ruby - 鞋子4,不能调用主app外的对象

python - 在 python 中——如何将项目转换为字典?

c# - 编译错误 :index out of range

recursion - Lisp 中的递归加法

ruby - 如果我的 case 语句的任何分支被调用,我可以设置一个变量吗?

ruby - 你将如何在 ruby​​ 中实现这个习惯用法?

将 OMML 转换为 MathML 的算法或代码

python递归pascal三角形

python - 递归函数在 Python 中不返回任何内容