我有一个我传递的参数,看起来像这样:
{{1}}
如何迭代此参数以获取每个项目的值?我知道我可以单独抓取每个项目,但在提交动态表单数据时,我不知道参数中的项目的确切数量。我怎样才能解决这个问题?
答案 0 :(得分:3)
hash = {"item_0"=>{"0"=>["address_1"], "1"=>["model 1"], "2"=>["ABC"], "3"=>["Off"], "4"=>["Status"]}, "item_1"=>{"0"=>["address_2"], "1"=>["model 1"], "2"=>["DEF"], "3"=>["On"], "4"=>["Status"]}, "item_2"=>{"0"=>["address_3"], "1"=>["model 1"], "2"=>["GHI"], "3"=>["On"], "4"=>["Status"]}}
hash.each do |k1, h1|
#eg: k1 = "item_0"; h1 = {"0"=>["address_1"], "1"=>["model 1"], "2"=>["ABC"], "3"=>["Off"], "4"=>["Status"]}
h1.each do |k2,arr|
#eg: k2 = "0"; arr = ["address_1"]
val = arr.first
puts "do something with k1 = #{k1.inspect}, k2 = #{k2.inspect}, val = #{val.inspect} here"
end
end
我使用类似的模式来请求更新多个对象,我通过这种结构发送params:
params = {:resources => {123 => {:name => "Foo", :address => "bar"}, 456 => {:name => "Boo", :address => "Far"}}}
然后在我的代码中我可以做
params[:resources].each do |id, attrs|
if resource = Resource.find_by_id(id)
resource.update_attributes(attrs)
end
end
可以用更长篇的方式写成
params[:resources].each do |id, attrs|
if resource = Resource.find_by_id(id)
attrs.each do |k,v|
resource.send("#{k}=", v)
end
resource.save
end
end
答案 1 :(得分:2)
要仅保留您想要的密钥,您可以使用Hash#keep_if
执行以下操作:
hsh = {"utf8"=>"✓",
"authenticity_token"=>"xx==",
"item_0"=>{"0"=>["address_1"], "1"=>["model 1"], "2"=>["ABC"], "3"=>["Off"], "4"=>["Status"]},
"item_1"=>{"0"=>["address_2"], "1"=>["model 1"], "2"=>["DEF"], "3"=>["On"], "4"=>["Status"]},
"item_2"=>{"0"=>["address_3"], "1"=>["model 1"], "2"=>["GHI"], "3"=>["On"], "4"=>["Status"]}}
hsh.keep_if {|k, v| k=~ /item_/ }
然后会返回:
{"item_0"=>{"0"=>["address_1"], "1"=>["model 1"], "2"=>["ABC"], "3"=>["Off"], "4"=>["Status"]},
"item_1"=>{"0"=>["address_2"], "1"=>["model 1"], "2"=>["DEF"], "3"=>["On"], "4"=>["Status"]},
"item_2"=>{"0"=>["address_3"], "1"=>["model 1"], "2"=>["GHI"], "3"=>["On"], "4"=>["Status"]}}
您可以使用Hash
循环播放each_pair
。每一对都参考例如代表键/值对的|k, v|
。从那里你可以做你喜欢的哈希。由于你的哈希是嵌套的,我画了这个例子:
hsh = {"item_0"=>{"0"=>["address_1"], "1"=>["model 1"], "2"=>["ABC"],"3"=>["Off"], "4"=>["Status"]},
"item_1"=>{"0"=>["address_2"], "1"=>["model 1"], "2"=>["DEF"], "3"=>["On"], "4"=>["Status"]},
"item_2"=>{"0"=>["address_3"], "1"=>["model 1"], "2"=>["GHI"], "3"=>["On"], "4"=>["Status"]}}
> hsh.each_pair {|k, v| v.each_pair {|j, w| puts w } }
address_1
model 1
ABC
Off
Status
address_2
model 1
DEF
On
Status
address_3
model 1
GHI
On
Status
Here's指向Hash#each_pair
的文档的链接。
有许多循环哈希的方法。例如,each_key
和each_value
,其功能与命名相同。