简体   繁体   中英

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

otherCount = @products.drop(3).inject(0) { |sum,count| sum, count }

My Ruby environment is 1.9.3.

products is an array of hashes elements. It has properties: productName and 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). Documentation I've found are either too brief in their explanation or use a different Ruby environment, which may likely be the problem. 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.

Change

inject(0) { |sum,count| sum, count }

to

inject(0) { |sum,p| sum + p['count'] }

Isolate the code

If you're having trouble integrating this, copy and paste these 2 lines into an irb session to verify this works:

a = [{'count' => 1},{'count' => 2},{'count' => 3}]
a.inject(0) { |sum,p| sum + p['count'] }
# => 6

Hopefully this helps bridge the gap.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM