I would like to understand how define_method
works and how to properly use the variables outside of the definition block. Here is my code:
class
As mentionned in comments this is down to closures - the block passed to define_method
captures the local variables from its scope (and not just their value as you found out).
for
doesn't create a new scope, so your method 'sees' the change to i
. If you use a block (for example with each) then a new scope is created and this won't happen. You just need to change your code to
class Test
def self.plugin
(1..2).each do |i|
define_method("test#{i}".to_sym) do
p i
end
end
end
plugin
end
which is basically what the question linked by Arup was about