2012-01-14 77 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