neanderslob
neanderslob

Reputation: 2693

Using variable in .map()

I'm attempting to write a helper that sums using nil values as zeros. Taking advantage of the following method from this answer.

items.map(&:some_field).sum(&:to_i)

The issue is that since I'm writing a helper, :some_field will need to be passed in as a variable. How do I then use that variable in .map? Something like the following:

items.map(&:send(field)).sum(&:to_i)

Any tips would be appreciated

Upvotes: 2

Views: 2215

Answers (2)

Rohit Jangid
Rohit Jangid

Reputation: 1115

You could go ahead using following code

items.map(&field).sum(&:to_i)

Note that i have just removed the ":" symbol. Here field is your variable

Upvotes: 6

Marek Lipka
Marek Lipka

Reputation: 51151

You should simply manually write block passed to map method:

items.map { |item| item.public_send(field) }.sum(&:to_i)

Blocks are closures in Ruby, so if there is field local variable in this scope, it will also be accessible inside of block.

Upvotes: 5

Related Questions