Using local variables in define_method

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 #=> 2  (I would expect 1)
ob.test2 #=> 2  (I would expect 2)

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.

+4
source share
1 answer

, - , define_method, ( , ).

for , "" i. (, ), , .

class Test
  def self.plugin
    (1..2).each do |i|
      define_method("test#{i}".to_sym) do
        p i
      end
    end
  end
  plugin
end

,

+6

All Articles