[英]syntax error, unexpected '}', expecting '='
otherCount = @products.drop(3).inject(0) { |sum,count| sum, count }
My Ruby environment is 1.9.3. 我的Ruby环境是1.9.3。
products
is an array of hashes elements. products
是散列元素的数组。 It has properties: productName
and count
. 它具有属性: productName
和count
。 I want to sum up the count values of all the hashes in the products
array (with the exception of the first 3 hashes). 我想对products
数组中所有哈希的计数值进行汇总(前三个哈希除外)。 Documentation I've found are either too brief in their explanation or use a different Ruby environment, which may likely be the problem. 我发现的文档说明太简短,或者使用其他Ruby环境,这可能是问题所在。 The code I wrote is written as per this document . 我写的代码是按照本文档编写的 。
I drop the first 3 elements, then call inject
, with an initial value of 0, carry over variable called sum
, and count
is the name of the field in each of the hashes whose value I want to add up. 我删除前三个元素,然后调用inject
,其初始值为0,并保留名为sum
变量,并且count
是每个要累加其值的哈希值中的字段名称。
Change 更改
inject(0) { |sum,count| sum, count }
to 至
inject(0) { |sum,p| sum + p['count'] }
If you're having trouble integrating this, copy and paste these 2 lines into an irb
session to verify this works: 如果您在集成时遇到问题,请将这两行复制并粘贴到irb
会话中以验证其是否有效:
a = [{'count' => 1},{'count' => 2},{'count' => 3}]
a.inject(0) { |sum,p| sum + p['count'] }
# => 6
Hopefully this helps bridge the gap. 希望这有助于弥合差距。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.