我有一个如下所示的数组
[{500 => {“id”=> 1,“name”=>“Hock Tong Bee Pte Ltd / Corner stone wines”, “created_at”=>星期四,2017年1月19日18:10:35 UTC +00:00,“updated_at”=>星期四, 2017-1-19 18:10:35 UTC +00:00,“website”=> nil,“status”=> nil, “industry_type_id”=> 1,“major_category_id”=> 1, “minor_category_id”=> 75,“save_as_draft”=> false,“company_id”=> 1}}, {600 => {“id”=> 2,“name”=>“Continental Wines”,“created_at”=>星期四,1月19日 2017 18:10:35 UTC +00:00,“updated_at”=>星期四,2017年1月19日18:10:35 UTC +00:00,“website”=> nil,“status”=> nil,“industry_type_id”=> 1,“major_category_id”=> 1,“minor_category_id”=> 75, “save_as_draft”=> false,“company_id”=> 2}}]
我从这个数组中获得500/600的密钥,我希望获得该对象。 我需要编写一个方法,我只传递键应该返回适当的对象。例如,如果我发送密钥是500,则结果应为
{“id”=> 1,“name”=>“Hock Tong Bee Pte Ltd / Corner stone wines”, “created_at”=>星期四,2017年1月19日18:10:35 UTC +00:00,“updated_at”=>星期四, 2017-1-19 18:10:35 UTC +00:00,“website”=> nil,“status”=> nil, “industry_type_id”=> 1,“major_category_id”=> 1, “minor_category_id”=> 75,“save_as_draft”=> false,“company_id”=> 1}
有人知道如何在Ruby中实现这一目标吗?
答案 0 :(得分:2)
我认为简单的reduce方法应该有效:
hash = [{500=>{"id"=>1, "name"=>"Hock Tong Bee Pte Ltd/ Corner stone wines", "created_at"=>"Thu, 19 Jan 2017 18:10:35 UTC +00:00", "updated_at"=>"Thu, 19 Jan 2017 18:10:35 UTC +00:00", "website"=>nil, "status"=>nil, "industry_type_id"=>1, "major_category_id"=>1, "minor_category_id"=>75, "save_as_draft"=>false, "company_id"=>1}}, {600=>{"id"=>2, "name"=>"Continental Wines", "created_at"=>"Thu, 19 Jan 2017 18:10:35 UTC +00:00", "updated_at"=>"Thu, 19 Jan 2017 18:10:35 UTC +00:00", "website"=>nil, "status"=>nil, "industry_type_id"=>1, "major_category_id"=>1, "minor_category_id"=>75, "save_as_draft"=>false, "company_id"=>2}}]
your_value = hash.reduce({}) { |h, v| h.merge v }[500]