tags:

views:

46

answers:

2

I have an issue dealing with a hash of objects. My hashes are player names, and the object has a property @name also.

I am trying to iterate over multiple players, and be able to use their methods and such with rather clean code. Here is how I create the hash:

puts "Who all is playing?"
gets.split.each do |p|
    players[p] = Player.new(p)
end

And then I want to iterate through the players like this, but it doesn't work.

players.each_key do |p_name, obj|
    puts obj.name + " turn"

However, this does work:

players.each_key do |p_name, obj|
    puts players[p_name].name + " turn"

On the first try, I get an error of obj being nil. Can someone explain why this won't work, and how to do it the way I would like to?

Thanks!

P.S. What is the correct terminology for the array or hash that I made? I come from PHP, so I think of it as an array (with hashes), but it technically isn't an array in Ruby?

+3  A: 

You want to use each_pair and not each_key. The method each_key only gives one argument to the block, which is the key. Therefore your obj remain unbound. each_pair on the other hand gives you both the key and the corresponding value.

grddev
Oh that is perfect! Is there really any reason to use each_key for anything then? (in general, as oppose to .each)
phoffer
@phoffer: `each` and `each_pair` are synonyms. If you only want to access the keys, there is a (minor) performance benefits to use `each_key` instead of `each`/`each_pair`
grddev
Ok then. The performance is negligible to me, but it is easiest to use `each_pair`, and that is why I am working in Ruby.
phoffer
+3  A: 

P.S. What is the correct terminology for the array or hash that I made? I come from PHP, so I think of it as an array (with hashes), but it technically isn't an array in Ruby?

It's called a Hash in Ruby, and it is not the same as an array. Hashes are created with:

my_hash = Hash.new

or

my_hash = {}

While arrays are done thusly:

my_array = Array.new

or

my_array = []

Ruby hashes are associative arrays, like "arrays" in PHP. Ruby arrays are more like traditional "C" arrays, in that they're indexed with integers.

zetetic
@zetetic Thank you for that. I was kind of thinking along those lines, but I was just really unsure of it. `players = {}` is what I had done to create my hash. I am glad you understand what I meant by I come from PHP.
phoffer