views:

58

answers:

2

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...

A: 

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.

Brian
Thanks Brian, but I had an attr_accessor
Tony R
A: 

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...

Tony R