合并数组中的哈希

时间:2017-06-21 16:50:11

标签: ruby-on-rails ruby ruby-on-rails-5

我是Ruby和Rails的新手,我遇到了需要创建哈希数组的情况。请参见下面的代码:

def self.v_and_c items
 result = []
 items.try(:each) do |item|
  result << item
  if item.is_parent_variation
    check_ancestor item
    result << { :item_variation => @variations }
    result << { :options => @options }
   elsif item.is_parent_customization
    check_ancestor item
    result << { :customizations => @customizations }
    result << { :ingredients => @ingredients }
   end
 end
 result
end

这是函数的输出:

{"items":[{"id":1,"name":"Cake"},{"item_variation":null},{"options":null}]}

但我想这样做。

{"items":[{"id":1,"name":"Cake","item_variation":null, "options":null} ]}

3 个答案:

答案 0 :(得分:0)

应该这样简单,使用.merge方法

def self.v_and_c items
 result = []
 items.try(:each) do |item|
  result << item
  if item.is_parent_variation
    check_ancestor item
    result = result.merge { :item_variation => @variations }
    result = result.merge { :options => @options }
   elsif item.is_parent_customization
    check_ancestor item
    result = result.merge { :customizations => @customizations }
    result = result.merge { :ingredients => @ingredients }
   end
 end
 result
end

答案 1 :(得分:0)

您可以尝试这样的事情:

def self.v_and_c items
 result = []
 items.try(:each) do |item|
  item_hash = {}.merge(item)
  if item.is_parent_variation
    check_ancestor item
    item_hash.merge!({ item_variation: @variations }).merge!({ options: @options})
  elsif item.is_parent_customization
    check_ancestor item
    item_hash.merge!({ customizations: @customizations }).merge!({ ingredients: @ingredients})
  end
   result.push(item_hash)
 end
 result
end

<强>说明: 对于循环的每次迭代,创建一个item_hash并合并其中的所有必需哈希值,然后将生成的哈希值推送到结果数组中。

指点很少:

  • 处理新的Ruby哈希语法
  • 如果在两者中都需要检查祖先,为什么不在外面进行检查?

答案 2 :(得分:0)

def self.v_and_c items
  [].tap do |result|
  items.try(:each) do |item|
    result_hash = item.dup
    if item.is_parent_variation
      check_ancestor item
      result_hash.merge!({ item_variation: @variations, options: @options })
    elsif item.is_parent_customization
      check_ancestor item
      result_hash.merge!({ customizations: @customizations, ingredients: @ingredients })
    end
    result << result_hash
  end
end