使用自定义格式将数组转换为哈希

时间:2012-04-09 09:36:23

标签: ruby arrays

有人可以帮我将以下数组转换为具有以下格式的哈希吗?

阵列

[["0", {"checkbox_2"=>"on"}], ["2", {"checkbox_1"=>"on"}]]

哈希

search=>{"checkbox_2"=>"on", "checkbox_1"=>"on"}

2 个答案:

答案 0 :(得分:2)

xs = [["0", {"checkbox_2"=>"on"}], ["2", {"checkbox_1"=>"on"}]]
search = {:search => xs.map { |n, h| h }.inject(:merge)}
# {:search=>{"checkbox_2"=>"on", "checkbox_1"=>"on"}}

答案 1 :(得分:1)

arr = [["0", {"checkbox_2"=>"on"}], ["2", {"checkbox_1"=>"on"}]] 
hash = Hash[arr.flatten.select{|e| e.is_a? Hash}.collect{|e| e.to_a.flatten}]
=> {"checkbox_2"=>"on", "checkbox_1"=>"on"}