我是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} ]}
答案 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并合并其中的所有必需哈希值,然后将生成的哈希值推送到结果数组中。
指点很少:
答案 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
端