hash

Normally,when ruby is not able to find the method,it usually raises
"NoMethodError: undefined method "methodname"".That's what we always stuck,nothing special.
Above all,because of Ruby is a kind of dynamic language,what it does exactly if it can't find the method is calling "method_missing" method and method_missing raises a NameError exception,what is the point? you're able to apply the method_missing method in your application and do something cool.When we use hash,we normally call hash["key"] or hash[:key].What if we would like to call it something like hash.key.And here is a bit tricky used of it.

  1. def method_missing( id, *args )
  2. if self[id].nil?
  3. m = id.to_s
  4. if /=$/ =~ m
  5. self[m.chomp!] = (args.length < 2 ? args[0] : args)
  6. else
  7. self[m]
  8. end
  9. else
  10. self[id]
  11. end
  12. end
  13. h = { "foo" => "bar",:blah => "thinkruby"}
  14. h.blah # => thinkruby
  15. h.foo # => bar

It's not bad,right?

Syndicate content