简体   繁体   中英

Using Proc with ruby hash merge results in

I'm trying to DRY up my code by using Procs. I have many lines that look like this (other lines may have fees, discounts, taxes, rather than revenue):

h.merge!({revenue: 500}){|key, old_val, new_val| old_val + new_val}

I tried to write a Proc that looks like this:

hproc = Proc.new {|key, old_val, new_val| old_val + new_val}

And simplify the first line by doing this:

h.merge!({revenue: 500})(&hproc)

However, I get the error:

syntax error, unexpected '(', expecting end-of-input
h.merge!({revenue:600})(&hproc)
                    ^
h.merge!({revenue: 500}, &hproc)

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