# Anything wrong with this? am I just making trouble?

**URL:** <https://www.ruby-forum.com/t/anything-wrong-with-this-am-i-just-making-trouble/121520>\
**Category:** Rails\
**Created:** [November 28, 2007, 5:48pm UTC](https://www.ruby-forum.com/t/anything-wrong-with-this-am-i-just-making-trouble/121520 "2007-11-28T17:48:01Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![uncle](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/e5b9ba/32.png) [@uncle](https://www.ruby-forum.com/u/uncle)\
**Post date:** [November 28, 2007, 5:48pm UTC](https://www.ruby-forum.com/t/anything-wrong-with-this-am-i-just-making-trouble/121520/1 "2007-11-28T17:48:01Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![uncle](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/e5b9ba/32.png) [@uncle](https://www.ruby-forum.com/u/uncle)\
**Post date:** [November 28, 2007, 6:15pm UTC](https://www.ruby-forum.com/t/anything-wrong-with-this-am-i-just-making-trouble/121520/2 "2007-11-28T18:15:31Z")

</div>

On 28 Nov 2007, at 16:47, uncle wrote:

> 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
