什么是将ruby哈希转换为数组的最佳方法

Chr*_*ier 5 ruby arrays hash

我有一个看起来像这样的ruby哈希

{ "stuff_attributes" => {
     "1" => {"foo" => "bar", "baz" => "quux"}, 
     "2" => {"foo" => "bar", "baz" => "quux"} 
   }
}
Run Code Online (Sandbox Code Playgroud)

我想把它变成一个看起来像这样的哈希

{ "stuff_attributes" => [
    { "foo" => "bar", "baz" => "quux"},
    { "foo" => "bar", "baz" => "quux"}
  ]
}
Run Code Online (Sandbox Code Playgroud)

我还需要保留键的数字顺序,并且键的数量可变.以上是超简化的,但我在底部包含了一个真实的例子.最好的方法是什么?

PS

它还需要递归

就递归而言,这是我们可以假设的:

1)需要操作的键将匹配/ _attributes $/2)哈希将有许多其他键不匹配/ _attributes $/3)哈希中的键将始终是数字4)_attributes哈希可以在任何其他键下的任何哈希级别

这个哈希实际上是来自控制器中的创建动作的params哈希.这是使用此例程需要解析的内容的真实示例.

{
    "commit"=>"Save", 
    "tdsheet"=>{
    "team_id"=>"43", 
    "title"=>"", 
    "performing_org_id"=>"10", 
    "tdsinitneed_attributes"=>{ 
        "0"=>{
            "title"=>"", 
            "need_date"=>"", 
            "description"=>"", 
            "expected_providing_organization_id"=>"41"
            }, 
        "1"=>{
            "title"=>"", 
            "need_date"=>"", 
            "description"=>"", 
            "expected_providing_organization_id"=>"41"
            }
        }, 
        "level_two_studycollection_id"=>"27", 
        "plan_attributes"=>{
            "0"=>{
                "start_date"=>"", "end_date"=>""
            }
        }, 
        "dataitem_attributes"=>{
            "0"=>{
                "title"=>"", 
                "description"=>"", 
                "plan_attributes"=>{
                    "0"=>{
                        "start_date"=>"", 
                        "end_date"=>""
                        }
                    }
                }, 
            "1"=>{
                "title"=>"", 
                "description"=>"", 
                "plan_attributes"=>{
                    "0"=>{
                        "start_date"=>"", 
                        "end_date"=>""
                        }
                    }
                }
            }
        }, 
    "action"=>"create", 
    "studycollection_level"=>"", 
    "controller"=>"tdsheets"
}
Run Code Online (Sandbox Code Playgroud)

Vin*_*ert 8

请注意,这可能很长,以测试转换前所有键是否为数字...

def array_from_hash(h)
  return h unless h.is_a? Hash

  all_numbers = h.keys.all? { |k| k.to_i.to_s == k }
  if all_numbers
    h.keys.sort_by{ |k| k.to_i }.map{ |i| array_from_hash(h[i]) }
  else
    h.each do |k, v|
      h[k] = array_from_hash(v)
    end
  end
end
Run Code Online (Sandbox Code Playgroud)