24

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!

0

3 Answers 3

51

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 Symbols as Hash keys rather than Strings because Symbols 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
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry.. I dont understand.. so what should @collection be?
3

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"]

Comments

1

You can do this:

@collection = [{ "firstname" => "Mark", "lastname" => "Martin", "age" => "24", "gender" => "M" }]

2 Comments

This does not solve the problem of the OP. Nor do I understand what problem you try to solve with the code you propose. Since this question still attracts visitors this answer can still confuse visitors. I would suggest to remove it.
@PaulvanLeeuwen I think you right, this answer more response to title of question, when question itself ask quite another thing. If we remove array from context of question at all, there will be still problem with access to hash element by key. So I would recommend renaming the question title to "How to access to Hash element properly in Ruby". Therefore I thought that some people came here exactly for "Create an Array of Hashes in Ruby" and for them it will be useful. So If didn't convince you I will immediately delete it ))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.