Contact iFingers

Finger Tips - a fistful of handy web notes

Monday, July 30, 2007

A fast dash with the Ruby Hash

A Hash or Hash Table as it is sometimes called is used throughout Ruby and Ruby on Rails development. A Hash is a data structure that can hold keys and values. Similar to an array, but not ordered.

(If you're using Mac OS X open up Terminal and type irb, then hit enter, to play along at home)

How to create a Hash

my_hash = {:car => "McLaren", :driver => "Fernando Alonso", :engine => "Mercedes-Benz"}

Get the value of a key

my_hash[:driver]

Will return, "Fernando Alonso"

Set a new value for a key

my_hash[:driver] = "Lewis Hamilton"

Return the Hash

my_hash

Will return:

{:car => "McLaren", :driver => "Lewis Hamilton", :engine => "Mercedes-Benz"}

Add a new key value pair to the hash

my_hash[:tyres] = "Bridgestone Potenza"

Return the Hash

my_hash

Will return:

{:car => "McLaren", :driver => "Lewis Hamilton", :engine => "Mercedes-Benz", :tyres => "Bridgestone Potenza"}

Labels: , ,

0 Comments:

Post a Comment

<< Home