Faery
Faery

Reputation: 4650

What is the name of the += method for hash?

I want to rewrite this:

my_hash['a'] += 5

in something like this:

my_hash. send (:[]+=, 'a', 5)

but :[]+= isn't working.

Is there a way to do this?

Upvotes: 1

Views: 88

Answers (2)

benjaminjosephw
benjaminjosephw

Reputation: 4417

How about:

my_array.send(:[]=, 'a', my_array['a'] + 5)

Upvotes: 3

Denis de Bernardy
Denis de Bernardy

Reputation: 78443

That's syntactic sugar for:

my_array['a'] = my_array['a'] + 5

So the method is + on the element (not the array), and [] and []= on the array itself. (Or more precisely here, on the hash.)

Upvotes: 2

Related Questions