2016-05-14 79 views
0

我有一个对象,视频。我想在Rails的.each循环中添加视频的id和持续时间。像下面 -将键值对添加到Rails中的对象中

videos = {} 

Products.each do |p, index| 
    videos << p.id => p.duration 
end 

为了得到一个样本集的结果是这样 -

videos = { 1: 2345, 2: 3456, 3: 4567 } 

回答

1

您应该使用each_with_index

videos = Hash.new 
Products.each_with_index do |p, index| 
    videos.merge(p.id => p.duration) 
end 
+0

啊!忘了做each_with_index,但是Hash.new和.merge是我一直在寻找的东西。感谢那! – Yasir