Ruby Hash bug help!
Question
I'm trying to create a Ruby Hash of objects, where the keys are the object @name member:
# m is an object with an @name instance variable (a string)
myHash = {}
myHash[m.name] = m
It's giving this error:
#<TypeError: can't convert String into Integer>
Anyone know why? I'm sure that m.name is a valid string...
Solution 2
Was accidentally reusing a variable name that was an array... oops!
For some reason I thought the hash was tricking me because I hadn't used one in Ruby before...
OTHER TIPS
Does this irb example help?
> class MyClass
> attr_reader :name
> def initialize
> @name = "myname"
> end
> end
=> nil
> m = MyClass.new
=> #<MyClass:0x47c3e0 @name="myname">
> puts m.name
myname
=> nil
> myHash = {}
=> {}
> myHash[m.name] = m
=> #<MyClass:0x47c3e0 @name="myname">
> puts myHash.inspect
{"myname"=>#<MyClass:0x47c3e0 @name="myname">}
=> nil
notice the attr_reader :name
which creates a getter method for name.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow