将键、值对添加到 Rails 中的对象
Adding key, value pair to object in Rails
我有一个对象,视频。我想在 Rails 中的 .each 循环中添加视频 ID 及其持续时间。类似下面的内容 --
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
我有一个对象,视频。我想在 Rails 中的 .each 循环中添加视频 ID 及其持续时间。类似下面的内容 --
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