【问题标题】:Ruby method to select property in possibly nested array of objects在可能嵌套的对象数组中选择属性的 Ruby 方法
【发布时间】:2015-08-18 21:01:16
【问题描述】:

我在尝试从数组中获取对象时遇到问题,其中给定的散列可能具有特定属性和特定值,或者嵌套散列也可能具有。

有没有一种方法可以返回具有我需要的密钥的特定哈希,或者当它没有时返回?

示例:我有这个完全虚构的结构:

  the_array = [
  {
    :is_father => true, 
    :seek_this => "01"  
  },
  {
    :is_uncle => false,
    :children => [
       {
         :seek_this => "09"
       },
       {
         :seek_this => "2a"
       }
    ]
  },
  {
    :random_property=> 3,
    :children => {
      :random_er => true,
      :children => [
        {
          :is_father => false,
          :children => [
             {
               :seek_this => "3b"
             },
             {
               :seek_this => "h1"
             }
          ]
        }
      ]
    }
  }
]

调用后

the_array
  .methodThatIDoNotKnow { |x| !x.seek_this.nil? } 
  .each do |hash_i_need|
  //operate on hash somehow
  hash_i_need.seek_this = 0xDEADBEEF
end

这是我所期望的:

  the_array = [
  {
    :some_key => true, 
    :seek_this => 0xDEADBEEF
  },
  {
    :some_other_key => false,
    :children => [
       {
         :seek_this => 0xDEADBEEF
       },
       {
         :seek_this => 0xDEADBEEF
       }
    ]
  },
  {
    :random_key: 3,
    :children => {
      :random_er => true,
      :children  => [
        {
          :is_father => false,
          :children  => [
             {
               :seek_this => 0xDEADBEEF
             },
             {
               :seek_this => 0xDEADBEEF
             }
          ]
        }
      ]
    }
  }
]

我知道这是我可以自己编码的东西,我只是想知道我是否需要或者是否有开箱即用的这种搜索功能。

谢谢!

【问题讨论】:

    标签: arrays ruby hash filter


    【解决方案1】:

    哈希上有一个fetch 方法,但它不会通过对象递归

    你可以使用这个answer 或者那里有很多深度获取示例。祝你好运!

    【讨论】:

      猜你喜欢
      • 2017-06-26
      • 1970-01-01
      • 2018-07-02
      • 1970-01-01
      • 2021-03-23
      • 2019-04-18
      • 2021-10-27
      • 2017-09-10
      • 2022-01-17
      相关资源
      最近更新 更多