Ruby 如何从数组的散列中获取散列数组
我一直在思考如何在ruby中执行下一个操作,但我是一个新手,无法找到解决方案 我有一个数组散列:Ruby 如何从数组的散列中获取散列数组,ruby,arrays,hash,Ruby,Arrays,Hash,我一直在思考如何在ruby中执行下一个操作,但我是一个新手,无法找到解决方案 我有一个数组散列: {文本:['1','2',位置:[1,2]} 我想要: [{text:'1',position:1},{text:'2',position:2}] 希望你能帮助我。 谢谢。获取键(:text,:positions)和值(数组): 然后,使用/获得您想要的: # values.transpose => [["1", 1], ["2", 2]] values.transpose.map {|vs|
{文本:['1','2',位置:[1,2]}
我想要:
[{text:'1',position:1},{text:'2',position:2}]
希望你能帮助我。谢谢。获取键(
:text
,:positions
)和值(数组):
然后,使用/获得您想要的:
# 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.
获取键(:text
,:positions
)和值(数组):
然后,使用/获得您想要的:
# 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.
将块与以下对象一起使用:
hash={text:['1','2',位置:[1,2]}
输出=[]
hash[:text].zip(hash[:position])do | a1,a2 |
输出[{:text=>1',:position=>1},{:text=>2',:position=>2}]
将块与以下内容一起使用:
hash={text:['1','2',位置:[1,2]}
输出=[]
hash[:text].zip(hash[:position])do | a1,a2 |
输出[{:text=>1',:position=>1},{:text=>2',:position=>2}]
另一种方式:
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}]
另一种方式:
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}]
嗨,阿鲁普,你好吗?嗨,阿鲁普,你好吗?