website stat

Ruby Hash with method access

Having a Hash with method access might be quite handy. For instance, if you're using it as a mock object to simulate some object that should be in place but isn't, it's way faster to use a Hash than load a fatty class with tons of methods.

In order to have method access one might make use of Ruby's meta-programming pills, namely doing something like this:

RUBY:
  1. inherits_hash_class.class_eval do
  2.   options.each_pair do |key, value|
  3.      define_method key do
  4.        value
  5.      end
  6.   end
  7. end

But Ruby developers were kind enough to add the OpenStruct to the core, so don't get fancy and just use this useful class.

RUBY:
  1. o = OpenStruct.new(:a => 1, :b => 2)
  2. o.a # => 1
  3. o.b = 2 # b = 2


No Responses to “Ruby Hash with method access”

Comments are closed.