I have included this extension to Hash in my rails app... class Hash def method_missing(name, value=nil) key = name.to_s.sub(/[=?!]$/,'''').to_sym self[key] = value if name.to_s[-1,1] == "=" return self[key] end end I basically lets a plane old Hash behave like the fancy OpenStruct, so you can do things like hash.amount = 10 instead of hash[:amount] 10. It uses method_missing to do its stuff.>> h = Hash.new=> {}>> h.a = 1=> 1>> h.b = 2=> 2>> h.c = 3=> 3>> pp h{:a=>1, :b=>2, :c=>3} => nil>> h.h = Hash.new=> {}>> h.h.a = 1=> 1>> h.h.b = 2=> 2>> h.h.c = 3=> 3>> pp h{:a=>1, :b=>2, :c=>3, :h=>{:a=>1, :b=>2, :c=>3}} => nil --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---
Frederick Cheung
2007-Nov-28 17:14 UTC
Re: Anything wrong with this? am I just making trouble?
On 28 Nov 2007, at 16:47, uncle wrote:> > I have included this extension to Hash in my rails app... > > class Hash > def method_missing(name, value=nil) > key = name.to_s.sub(/[=?!]$/,'''').to_sym > self[key] = value if name.to_s[-1,1] == "=" > return self[key] > end > end > > I basically lets a plane old Hash behave like the fancy OpenStruct, so > you can do things like hash.amount = 10 instead of hash[:amount] > 10. It uses method_missing to do its stuff.I suppose the danger is that the day you do hash.delete_if! instead of getting a no method error it will just work and lead to a less easy to understand error further down the road. Fred> > >>> h = Hash.new > => {} >>> h.a = 1 > => 1 >>> h.b = 2 > => 2 >>> h.c = 3 > => 3 >>> pp h > {:a=>1, :b=>2, :c=>3} > => nil >>> h.h = Hash.new > => {} >>> h.h.a = 1 > => 1 >>> h.h.b = 2 > => 2 >>> h.h.c = 3 > => 3 >>> pp h > {:a=>1, :b=>2, :c=>3, :h=>{:a=>1, :b=>2, :c=>3}} > => nil > > >--~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---