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|
开发者_Python百科 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?
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.
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.
精彩评论