Ruby on Rails:每个循环,在数组内用逗号分隔结果散列



我试图创建一个哈希使用每个循环如下:

[
  hash = session[:cart].each do |product|
  price = product[0].price.to_i*100
  {
    name: product[0].name, description: product[0].description, quantity: product[1], amount: product[0].price
  }, #Is it possible to add a comma here? Doing this normally causes an error
  end
]

应该产生如下输出

 [
   {name: "Hellow", description: "Many Hellows", quantity: 1, price: 1000},
   {name: "Hellow", description: "Many Hellows", quantity: 1, price: 1000}
 ]

您想要.map,而不是.each。每一个迭代。Map把一件事翻译成另一件事

[
  session[:cart].map do |product|
    price = product[0].price.to_i*100
    {
      name: product[0].name,
      description: product[0].description,
      quantity: product[1],
      amount: product[0].price
    } 
  end
]

最新更新