2012-01-14 53 views
0

我試圖創建收件人列表通過賦予它做在外部請求發送給一個變量如下:Rails的語法錯誤,每個循環爲變量賦值

recipients = @items.each do |item| 
    {"email"=>"#{Recipient.find_by_id(item.recip_id).email}", "amount"=>"#{item.price}"}, 
end 

,但我得到這個錯誤:

syntax error, unexpected ',', expecting '}' 

我知道我所做的不是正確的語法。我是一個Ruby新手,所以有人可以幫我找出正確的語法嗎?

編輯:感謝您的輸入。但是如果我需要爲每件物品做兩次哈希值呢?

recipients = @items.map do |item| 
    {"email"=>"#{Recipient.find_by_id(item.recip_id).email}", "amount"=>"#{item.price}"}, 
    {"email"=>"#{Store.find_by_id(item.recip_id).email}", "amount"=>"#{item.price}"} 
end 
+0

嘗試刪除,在散列聲明的結尾。 – 2012-01-14 05:04:36

回答

1

如果你想從你的map塊返回多個哈希值,那麼你會更好切換到each_with_object

Iterates the given block for each element with an arbitrary object given, and returns the initially given object.

因此,像這樣:

recipients = @items.each_with_object([]) do |item, a| 
    a << {"email"=>"#{Recipient.find_by_id(item.recip_id).email}", "amount"=>"#{item.price}"} 
    a << {"email"=>"#{Store.find_by_id(item.recip_id).email}", "amount"=>"#{item.price}"} 
end 
+0

啊!這最終解決了它。我假設<<運算符將散列追加到? – varatis 2012-01-14 06:31:18

+0

@varatis:是的,['Array#<<'](http://ruby-doc.org/core-1.9.3/Array.html#method-i-3C-3C)與['Array #push'](http://ruby-doc.org/core-1.9.3/Array.html#method-i-push)。 – 2012-01-14 06:52:30

3

問題在於散列末尾的逗號。另外,如果您想將電子郵件和金額存儲在收件人中,則應使用地圖。這將返回哈希數組電子郵件和金額:

recipients = @items.map do |item| 
    {"email"=> Recipient.find_by_id(item.recip_id).email, "amount"=> item.price} 
end 

而且,你可能會注意到,我並不需要通過電子郵件的價值和價格作爲一個字符串。

+0

好的謝謝。但是如果我需要爲每個項目做兩次哈希(即兩個電子郵件 - 數量對)呢?我在這個問題上舉了一個例子。對不起 - 我意識到我以前沒有問過這個,但是我最近意識到每個項目都需要兩個哈希值。 – varatis 2012-01-14 05:14:58

+0

@varatis:你可以從'map'塊返回一個兩個元素的數組,然後'flatten'結果或切換到'each_with_object([])',並將兩個入口放到塊內部的數組上。 – 2012-01-14 05:25:03

+0

使用散列的問題是他們將需要一個唯一的密鑰。因此,關鍵電子郵件只能有一個值鍵。一種方法是使用哈希散列。就像{「1」=> {「email」=>「abc」,「amount」=>「xyz」},「2」=> {「email」=>「pqr」,「amount」=>「lmn 「}},其中1和2可以是項目的ID。 – 2012-01-14 05:28:43