user1136342
user1136342

Reputation: 4941

Why does my array value in my map not get updated?

If I have:

map = Hash.new { [] }

It shows that map['a'] (or any other arbitrary key) is initialized to [], as I expected. But when I try to update it with:

map['a'] << 15

Then my map doesn't change at all. Is it supposed to? Am I doing something incorrectly? Is this just not supported when the actual key does not exist, even though it's supposed to have a default value?

Upvotes: 0

Views: 37

Answers (2)

Motombo
Motombo

Reputation: 1787

You can use a block to intiialize the hash {|h,k| h[k] = [] }

Or you can do map['a'] = 15 this will allow map to be a hash with a pointing to 15

Upvotes: 1

user229044
user229044

Reputation: 239432

That isn't how you use a block to initialize a hash. The block receives the new hash, and the key being accessed, and leaves it up yo you to define the associated value.

You need the following:

map = Hash.new { |hash,key| hash[key] = [] }

Upvotes: 1

Related Questions