Ruby Hash with method access
- Published February 7th, 2008 in Tips & Tricks, Ruby
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:
-
inherits_hash_class.class_eval do
-
options.each_pair do |key, value|
-
define_method key do
-
value
-
end
-
end
-
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.
-
o = OpenStruct.new(:a => 1, :b => 2)
-
o.a # => 1
-
o.b = 2 # b = 2




No Responses to “Ruby Hash with method access”