Snowcrash
Snowcrash

Reputation: 86097

Ruby - setting a value in a hash

Anyone care to explain why I'm getting an error here:

[~]$ irb
>> h = Hash
=> Hash
>> h["a"] = 100
NoMethodError: undefined method `[]=' for Hash:Class
from (irb):2

but not here:

>> h = {'dog' => 'canine'}
=> {"dog"=>"canine"}
>> h["a"] = 100
=> 100

Upvotes: 1

Views: 139

Answers (2)

Boris Strandjev
Boris Strandjev

Reputation: 46943

You need to write h = Hash.new and everything will be ok. Otherwise you are referencing methods for the class, not an instance. This works as you expect it:

h = Hash.new
h['dog'] = 5

Upvotes: 3

Douglas F Shearer
Douglas F Shearer

Reputation: 26488

You need to call Hash.new. With your code you are assigning the Hash class to h, not an instance of it.

irb(main):001:0> h = Hash
=> Hash
irb(main):002:0> h.class.name
=> "Class"
irb(main):003:0> h = Hash.new
=> {}
irb(main):004:0> h.class.name
=> "Hash"

Upvotes: 7

Related Questions