tags:

views:

138

answers:

2

i have the following

class test
 hash={}

  def printHash 
      puts hash[1]
      puts hash[2]
      puts hash[3]
    end
end

test.new.printHash

this prints:

1 
0 
1

Why does this happen? how can i test whether or not i have put something in that spot of the hash? or am i missing something

+9  A: 

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

Pesto
thanks alot for all the explaination. trying to learn ruby through euler problems, and this is a bit of information i would never get from this. Thanks.
Nuno Furtado
It _is_ a very good explanation. Before tackling the Euler problems, you might try the Ruby Koans: http://github.com/edgecase/ruby_koans/tree/master
James A. Rosen
A: 

Basically 'hash' is out of scope, what you are referencing in your printHash function is a different object altogether, normally it would be nil (a new unassigned object) but as Pesto points out 'hash' is a built in function - somewhat confusing this explanation.

By putting an '@' sign in front of the your variable and assigning it in the initialize method (which is called after 'new') it becomes available in the entire instance of your object.

Kris