如何在rails

时间:2016-08-06 23:02:25

标签: ruby-on-rails multidimensional-array

我正在努力在我的项目中实现searchkick并使搜索工作正常。现在我尝试实现过滤系统并使用aggs显示过滤条件。 aggs返回的数组对我来说有点复杂,并试图找出如何循环遍历特定部分。继承了它返回的aggs:

  

{"技术" = GT; {" doc_count_error_upper_bound&#34 =大于0,   " sum_other_doc_count" => 0,"水桶" => [{"键" =>"油炸",   " doc_count" => 1},{"键" =>"灼热"," doc_count" => 1}]} ,   "成分" = GT; {" doc_count_error_upper_bound&#34 =大于0,   " sum_other_doc_count" => 0,"水桶" => [{"键" =>" Furikake,用于服务",   " doc_count" => 1},{" key" =>"犹太盐和黑胡椒",   " doc_count" => 1},{" key" =>" Salmon fillets"," doc_count" => 1},   {" key" =>"鳄梨,切块"," doc_count" => 1},{"键" =>& #34;煮熟的白色   饭"," doc_count" => 1},{"键" =>"日本黄瓜"," doc_count" =大于1},   {" key" =>" teriyaki sauce"," doc_count" => 1},{" key" =>&# 34;到8个大葱,   切成薄片"," doc_count" => 1},{"键" =>"植物油",   " doc_count" => 1}]},"菜肴" => {" doc_count_error_upper_bound" => 0,   " sum_other_doc_count" => 0,"水桶" => [{"键" =>"亚洲",   " doc_count" => 1},{"键" =>"日语"," doc_count" => 1}]} }

我如何编写一个do循环来循环浏览菜肴部分并从桶中提取个人名称和数量:

  

"美食" = GT; {" doc_count_error_upper_bound&#34 =大于0,   " sum_other_doc_count" => 0,"水桶" => [{"键" =>"亚洲",   " doc_count" => 1},{"键" =>"日语"," doc_count" => 1}]} }

所以基本上我想要一个如下所示的列表: 亚洲(1) 日本(1)

1 个答案:

答案 0 :(得分:1)

你拥有的是带有数组元素的哈希。这取决于你想要的是什么,但假设你为它赋了一个变量my_hash,你可以这样做:

my_hash['cuisines']['buckets'].reduce('') do |r, h| 
  r += "#{h['key']} (#{h['doc_count']}) "
end
=> "Asian (1) Japanese (1) "