how to monkeypatch Hash's []= method

13 views
Skip to first unread message

Harold

unread,
Jan 6, 2009, 6:36:48 PM1/6/09
to Ruby on Rails: Talk
I'm trying to monkeypatch the []= method in the Hash class:

Hash.class_eval do
def []_with_feature=(a,b)
puts 'foo'
end
alias_method_chain :[]=, :feature
end

Something is wrong with the syntax, but I can't figure out what. The
alias_method_chain method does look for punctuation (= in this case)
and expects it to be at the end of the aliased method ([]
_with_feature=), but I get the following syntax error:

SyntaxError: compile error
(irb):5: syntax error, unexpected ')', expecting '='
(irb):7: syntax error, unexpected kEND, expecting ')'
(irb):9: syntax error, unexpected kEND, expecting ')'

Any ideas?

Thanks,
-H

Frederick Cheung

unread,
Jan 6, 2009, 6:49:13 PM1/6/09
to rubyonra...@googlegroups.com

On 6 Jan 2009, at 23:36, Harold wrote:

>
> I'm trying to monkeypatch the []= method in the Hash class:
>

doesn't seem to be anything to do with alias_method_chain - just
sticking
def []_with_feature=(a,b)
puts 'foo'
end

into irb causes similar errors. You'll just have to skip alias method
chain this time.

Fred

Harold A. Giménez Ch.

unread,
Jan 6, 2009, 6:56:01 PM1/6/09
to rubyonra...@googlegroups.com
Thanks for the response.

So how in the world is this implemented? The []= method's source code is in C. Other classes override it in a subclass, which works fine, but how would I go about implementing a method that works like the Hash class' []= method?

I'm not sure what you mean by "skipping alias_method_chain" this time. If I do

alias :[]_without_feature=, :[]=
alias :[]=, :[]_with_feature

I get the same error, as expected. So how would I go about changing this method's behavior?

Thanks again,
-H

Frederick Cheung

unread,
Jan 6, 2009, 7:20:56 PM1/6/09
to rubyonra...@googlegroups.com

On 6 Jan 2009, at 23:56, Harold A. Giménez Ch. wrote:

> Thanks for the response.
>
> So how in the world is this implemented? The []= method's source
> code is in C. Other classes override it in a subclass, which works
> fine, but how would I go about implementing a method that works like
> the Hash class' []= method?
>
> I'm not sure what you mean by "skipping alias_method_chain" this
> time. If I do
>
> alias :[]_without_feature=, :[]=
> alias :[]=, :[]_with_feature
>
> I get the same error, as expected. So how would I go about changing
> this method's behavior?
>

just call it square_bracket_without feature or something like that.
the problem isn;t the method aliasing it's defining a method called
[]_with_feature=

Fred

Harold A. Giménez Ch.

unread,
Jan 6, 2009, 9:38:43 PM1/6/09
to rubyonra...@googlegroups.com
I was focusing on the "=" being the problem... Worked nicely. Many thanks!
Reply all
Reply to author
Forward
0 new messages