From: Rick DeNatale Date: 2010-02-04T12:01:16+09:00 Subject: Re: hooking subscript operations in a hash On Wed, Feb 3, 2010 at 9:38 PM, Ralph Shnelvar wrote: > In order to help debug something, I'd like to hook the hash subscript operation. > > I've tried this (and several variants) in irb ... but it doesn't do what I want it to. > > > module RalphMod >  def []=(index, value) >    p index >    p value >    if index == 'PATH_INFO' and value == '/undefined' >      puts 'found it!' >    end >    super index, value >  end > end > > class Hash >  extend RalphMod > end > > env = {} > env['X'] = 'Y' > env['PATH_INFO'] = '/undefined' > > > The values are not displayed and 'found it!' is also not displayed. A few problems with this code. First class Hash extend RalphMod end makes the method in RalphMod a method of the Hash class object not hash instances. The way to do that would be class Hash include RalphMod end but this wouldn't work either because methods in included modules come after methods defined in the class, so you'll still invoke the original []= method. What you want is something like this: module RalphMod def []=(index, value) p index p value if index == 'PATH_INFO' and value == '/undefined' puts 'found it!' end super index, value end end env = {} env.extend RalphMod env['X'] = 'Y' env['PATH_INFO'] = '/undefined' This effectively inserts your module between the instance of Hash referenced by the variable env and it's class. -- Rick DeNatale Blog: http://talklikeaduck.denhaven2.com/ Twitter: http://twitter.com/RickDeNatale WWR: http://www.workingwithrails.com/person/9021-rick-denatale LinkedIn: http://www.linkedin.com/in/rickdenatale