0
我有一個對象,視頻。我想在Rails的.each循環中添加視頻的id和持續時間。像下面 -將鍵值對添加到Rails中的對象中
videos = {}
Products.each do |p, index|
videos << p.id => p.duration
end
爲了得到一個樣本集的結果是這樣 -
videos = { 1: 2345, 2: 3456, 3: 4567 }
我有一個對象,視頻。我想在Rails的.each循環中添加視頻的id和持續時間。像下面 -將鍵值對添加到Rails中的對象中
videos = {}
Products.each do |p, index|
videos << p.id => p.duration
end
爲了得到一個樣本集的結果是這樣 -
videos = { 1: 2345, 2: 3456, 3: 4567 }
您應該使用each_with_index
:
videos = Hash.new
Products.each_with_index do |p, index|
videos.merge(p.id => p.duration)
end
啊!忘了做each_with_index,但是Hash.new和.merge是我一直在尋找的東西。感謝那! – Yasir