Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HOW-TO Create an Array of Hashes in Ruby

Tags:

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!

like image 893
thedeepfield Avatar asked Jan 28 '11 08:01

thedeepfield


People also ask

How do you hash an array in Ruby?

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.

What is hash array?

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.

How do you create a hash in Ruby?

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.


1 Answers

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 
like image 177
Jacob Relkin Avatar answered Sep 20 '22 13:09

Jacob Relkin