Wednesday, 3 September 2008

Ruby Hashes

Ruby uses hashes a lot to pass data around, and one reason for that is that they are just so easy to use. A hash is a object that contains a number of name-value pairs; a dictionary. A hash with a single entry is created like this:
h = {name1 => value1}

In practice, the name is usually a symbol, and the value often a string, so this would be the usual format:
h = {:name1 => 'value1'}

For multiple entries, separate with commas.
h = { :name1 => 'value1', :name2 => 'value2', :name3 => 'value3' }

In method calls the curly brackets seem not to be required or even desired. This can make it seem as though the method takes several parameters rather than a single hash; I think that is deliberate.

New name-value pairs can be added
h[:newname] = 'new value' :newname, 'new value'

Values can be accessed like an array:
value = h[:name1]
h[:name1] = 'new value'
h[:name1] = nil

Some web sites suggest the last of these will delete the entry; not so! To delete, use the delete method:

However, accessing the key with the value is not trivial (as far as I can see). Here are two options:
h.find{ |k,v| == :value1 }[0]

To determine if a hash has a certain key, do this:
h.key? :my_key

You can loop through a hash with the each method. This example outputs each name-value pair (I believe the order is arbitrary).
h.each { |x,y| puts "Name #{x} Value #{y}" }

The delete_if method iterates through the hash and removes any entry for which the block evaluates to true. Note that as with the delete_if method in Aaray, this does not conform to the convention of an explanation mark for methoids that change the original.

Useful article:

By the way, Rails uses HashWithIndifferentAccess, which is special as it allows strings and symbols to be used interchangeably as keys when accessing values.

Struggling with Ruby: Contents Page

No comments: