Using local variables in define_method

前端 未结 1 407
攒了一身酷
攒了一身酷 2021-01-13 19:29

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         


        
1条回答
  •  粉色の甜心
    2021-01-13 20:12

    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

    0 讨论(0)
提交回复
热议问题