【问题标题】:Ruby Nested Hash MergeRuby 嵌套哈希合并
【发布时间】: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_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

【问题讨论】:

  • 无耻插件:我已经构建了 gem iteraptor 来服务于这个目的。
  • 只需点击“编辑”按钮。您可以在这样做后删除您的评论,我也会这样做。

标签: ruby algorithm recursion hash


【解决方案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的更新值。

【讨论】:

  • 根据我从问题中收集到的信息,:properties 在哈希中的位置事先不会知道。因此,不能保证我们可以通过hey[:some_key]到达:properties
  • 前面的评论是对的,问题是:properties 可以在散列中的任何地方,嵌套你可以想象的尽可能多的级别......并且在其中会发生魔法:)。这是我发布的示例代码的 repl.it repl.it/@chdezmar/Nested-hash-merge
  • @user3574603,我看你是对的,所以我编辑了我的代码。我很高兴看到我的理解是错误的,因为这是一个更有趣的问题。
猜你喜欢
  • 2019-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-16
  • 2019-11-21
  • 2015-11-22
  • 1970-01-01
相关资源
最近更新 更多