How are variables bound to the body of a define_method?

Posted by Chris on Stack Overflow See other posts from Stack Overflow or by Chris
Published on 2010-01-08T17:49:49Z Indexed on 2010/05/28 13:11 UTC
Read the original article Hit count: 249

Filed under:
|
|

While trying to brush up my Ruby skills I keep running across this case which I can't figure out an explanation for by just reading the API docs. An explanation would be greatly appreciated. Here's the example code:

for name in [ :new, :create, :destroy ]
  define_method("test_#{name}") do
    puts name
  end
end

What I want/expect to happen is that the name variable will be bound to the block given to define_method and that when #test_new is called it will output "new". Instead each defined method outputs "destroy" -- the last value assigned to the name variable. What am I misunderstanding about define_method and its blocks? Thanks!

© Stack Overflow or respective owner

Related posts about ruby

Related posts about reflection