Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Hash Referencing Hack for Ruby (See related posts)

Hash Hacks:
1. Method Missing hack to allow easy referencing.
I can never remember whether the Hash i am playing with has symbols for keys or
strings. I also dont like typing the brackets (not all text editors have the
cool "close brace" feature). That's why i came up with this method missing hack.
Instead of explaining what it does, I'll just show you.

Example:
hsh = {"project"=>
{ "prototype_url"=>nil,
"designer_id"=>2,
"finished_at"=>nil, "phone_number"=>"512225555",
"website"=>"http://www.ggg.com",
"first_name"=>"test",
}
}
hsh.project
#=> {"prototype_url"=>nil, "designer_id"=>2, "finished_at"=>nil, "phone_number"=>"512225555", "website"=>"http://www.ggg.com", "first_name"=>"test"}

hsh.project.prototype_url #=> nil
hsh.project.designer_id #=> 2
hsh.project.first_name #=> test

class Hash    		
  def method_missing(method_id, *args, &block)
    method_name = method_id.to_s
    check = self.stringify_keys
    if check.keys.include?(method_name)
      check[method_name]
    else
      super
    end
  end
end




I have packaged this and other useful hacks into a plugin at http://blog.djdossiers.com/articles/2007/03/31/new-rails-plugin-jakes-toolbox

Peace

--jake

You need to create an account or log in to post comments to this site.


Click here to browse all 4857 code snippets

Related Posts