Intridea Development Blog
Bending Ruby (Part I) - An User-friendly Hash using method_missing
There’s been a lot of talk about method_missing lately. Let’s do a little example that leverages this freaky but neat little method in our quest to bend Rails to our will. The following code is a handy trick that lets you access key values in a Hash as regular class methods.
class Hash
def method_missing(method, *params)
method = method.to_sym
return self[method] if self.keys.collect(&:to_sym).include?(method)
super
end
end
If you have a key called :name, then my_hash[:name] and my_hash.name will now give the same result. If you call some key that doesn’t exist, then the super call tells Object to throw a generic NoMethodError. Neat, no?
P.S. the collect(&:to_sym) shortcut used above actually evaluates to collect{|x| x.to_sym} in Rails. This functionality is not available in Ruby, but it can easily be replicated by overriding the Symbol class, like so:
class Symbol
def to_proc(*args)
Proc.new { |*args| args.shift.__send__(self, *args) }
end
end
Bending Ruby will be a series of posts that will build on one another.
The Intridea Blogs
Blog Archive
- June 2009 (3)
- May 2009 (1)
- April 2009 (3)
- March 2009 (8)
- February 2009 (9)
- January 2009 (2)
- December 2008 (1)
- November 2008 (1)
- October 2008 (2)
- July 2008 (5)
- June 2008 (8)
- April 2008 (4)
- March 2008 (1)
- February 2008 (4)
- January 2008 (4)
- December 2007 (3)
- November 2007 (3)
- October 2007 (4)
- September 2007 (2)
- August 2007 (3)
Pradeep Elankumaran