I would like to understand how it works define_methodand how to properly use variables outside the definition block. Here is my code:
class Test
def self.plugin
for i in 1..2
define_method("test#{i}".to_sym) do
p i
end
end
end
plugin
end
ob = Test.new
ob.test1
ob.test2
It seems that in methods, test1and the test2value is inot replaced during the definition, but is calculated directly in place when the method is called. Thus, we see only the last value i, which 2. But where does Ruby get this value from? And is there a way to let me test#{i}print i?
In this particular case, I could make a workaround using__method__ , but there is probably a better solution.
source
share