Reputation: 6196
New to ruby and I'm trying to create an array of hashes (or do I have it backwards?)
def collection
hash = { "firstname" => "Mark", "lastname" => "Martin", "age" => "24", "gender" => "M" }
array = []
array.push(hash)
@collection = array[0][:firstname]
end
@collection does not show the firstname for the object in position 0... What am I doing wrong?
Thanks in advance!
Upvotes: 24
Views: 73144
Reputation: 969
You can do this:
@collection = [{ "firstname" => "Mark", "lastname" => "Martin", "age" => "24", "gender" => "M" }]
Upvotes: 1
Reputation: 163228
You're using a Symbol
as the index into the Hash
object that uses String
objects as keys, so simply do this:
@collection = array[0]["firstname"]
I would encourage you to use Symbol
s as Hash
keys rather than String
s because Symbol
s are cached, and therefore more efficient, so this would be a better solution:
def collection
hash = { :firstname => "Mark", :lastname => "Martin", :age => 24, :gender => "M" }
array = []
array.push(hash)
@collection = array[0][:firstname]
end
Upvotes: 51
Reputation: 2469
You have defined the keys of your hash as String
. But then you are trying to reference it as Symbol
. That won't work that way.
Try
@collection = array[0]["firstname"]
Upvotes: 3