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!
In Ruby, a hash is a collection of key-value pairs. A hash is denoted by a set of curly braces ( {} ) which contains key-value pairs separated by commas. Each value is assigned to a key using a hash rocket ( => ). Calling the hash followed by a key name within brackets grabs the value associated with that key.
An array of hashes is useful when you have a bunch of records that you'd like to access sequentially, and each record itself contains key/value pairs. Arrays of hashes are used less frequently than the other structures in this chapter.
In Ruby you can create a Hash by assigning a key to a value with => , separate these key/value pairs with commas, and enclose the whole thing with curly braces.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With