1. Computing

Spotlight on Gems: Dynahash

By

The following article is written for the 0.3.2 version of the dynahash gem. Example code may not work with future versions.

The dynahash gem allows you to access hash members as if they were attributes. For example, given the hash {:key => 'value'}, you could access the value with hash.key instead of hash[:key].

This is implemented using method_missing, so any keys that share a name with a method in the Hash or Object class (or any other parents or methods from mixins) will need to be accessed the traditional way.

The dynahash gem is a pure-Ruby gem, you can install it as you would any other gem with gem install dynahash.

The following example demonstrates dynahash.


require 'dynahash'

hulk = {
  name:"Bruce Banner",
  alias:"The Incredible Hulk",
  alignment:"Good"
}

puts "My name is #{hulk.name}"
puts "You probably know me as #{hulk.alias}, who fights for #{hulk.alignment}"
  1. About.com
  2. Computing
  3. Ruby
  4. Tutorials
  5. Spotlight on Gems: Dynahash

©2014 About.com. All rights reserved.