合并红宝石中的两个哈希值

时间:2019-06-19 17:44:33

标签: ruby-on-rails ruby

我有两个哈希集合

and_filters = [{:filter=>:brand, :value=>"Fila"}, {:filter=>:brand, :value=>"Adidas"}]
or_filters = [{:filter=>:gender, :value=>"Hombre"}]

我需要像下面的结构

:_or => [
  { :_and => [
    {:gender => "Hombre"}, 
    {:brand => "Adidas"}] 
  }, 
  { :_and => [
    {:gender=>"Hombre"}, 
    {:brand=>"Fila"}] 
  }
]

为此我做了

query[:_or] = []
or_filters.each do |or_f|
  query[:_or] << {
    :_and => [
      and_filters.map do |and_f|
        {and_f[:filter] => and_f[:value]}
      end
      { or_f[:filter] => or_f[:value] }
    ]
  }
end

但出现错误预期:{显示在代码中。显然第二个循环在语法上很差

3 个答案:

答案 0 :(得分:1)

这不是很漂亮,但是我相信这可以达到预期的效果:

{_or: or_filters.each_with_object([]) do |or_filter, or_filter_ary|
    or_filter_hsh = {or_filter[:filter] => or_filter[:value]}
    and_filters.each do |and_filter|
      and_filter_hsh = {and_filter[:filter] => and_filter[:value]}
      or_filter_ary << {_and: [or_filter_hsh, and_filter_hsh]}
    end
  end
}

哪个给:

{:_or => [
  { :_and => [
    {:gender=>"Hombre"}, 
    {:brand=>"Fila"}
  ]}, 
  { :_and => [
    {:gender=>"Hombre"}, 
    {:brand=>"Adidas"}
  ]}
]}

答案 1 :(得分:1)

您似乎想要给定and_filters与给定or_filters的每种组合。在这种情况下,假设您不关心订单(:gender之前的:brand与其他情况无关)Array#product是您的朋友:

result = {
  _or: and_filters.product(or_filters).map do |a|
    { _and: a.map {|filter:, value:| { filter => value }} }
  end
}
# => {
#      :_or => [
#        {:_and => [{:brand=>"Fila"}, {:gender=>"Hombre"}]},
#        {:_and => [{:brand=>"Adidas"}, {:gender => "Hombre"}]}
#      ]
#    }

查看有关repl.it的实际操作:https://repl.it/@jrunning/HorizontalDirectCharmap

答案 2 :(得分:0)

那就是我想要的

query = {}
query[:_or] = or_filters.map do |or_f|
  and_filters_aux = and_filters.dup
  and_filters_aux << or_f
  { :_and => and_filters_aux.map{|hsh| {hsh[:filter] => hsh[:value]} } }
end

https://repl.it/repls/ShyLateClients