我一直在思考如何在ruby中进行下一步操作,但我是新手,我无法得到解决方案。
我有一个数组哈希:
{text: ['1','2'], position: [1,2]}
我希望:
[{text: '1', position: 1},{text: '2', position: 2}]
希望你能帮帮我 感谢。
答案 0 :(得分:3)
获取密钥(:text
,:positions
)和值(数组):
h = {text: ['1','2'], position: [1,2]}
keys, values = h.to_a.transpose
# keys => [:text, :position]
# values => [["1", "2"], [1, 2]]
然后,使用Array#transpose
/ Array#zip
来获得您想要的内容:
# values.transpose => [["1", 1], ["2", 2]]
values.transpose.map {|vs| keys.zip(vs).to_h }
# => [{:text=>"1", :position=>1}, {:text=>"2", :position=>2}]
# values.transpose.map {|vs| Hash[keys.zip(vs)] }
# ^ Use this if `to_h` is not available.
答案 1 :(得分:2)
将块与#zip
:
hash = {text: ['1','2'], position: [1,2]}
output = []
hash[:text].zip(hash[:position]) do |a1, a2|
output << {text: a1, position: a2}
end
output # => [{:text=>"1", :position=>1}, {:text=>"2", :position=>2}]
答案 2 :(得分:1)
另一种方式:
h = {text: ['1','2'], position: [1,2]}
h.map { |k,v| [k].product(v) }.transpose.map(&:to_h)
#=> [{:text=>"1", :position=>1}, {:text=>"2", :position=>2}]