You're well off the mark, but it appears to be doing something because hash
is a builtin function which returns a Fixnum hashcode for the object. When you use square brackets on a Fixnum, you get the value of the specific bit. What you want to do is to create an instance variable, which starts with the sigil @
. Also, you have to create instance variables within a method, so we'll use the one that's called whenever an object of the class is created, initialize
:
class Test
def initialize
@hash = {}
end
def printHash
puts @hash[1]
puts @hash[2]
puts @hash[3]
end
end
Now you'll find this prints nil
for all three. To test whether a hash has a value for a specific key, you can use has_key?
.