title: How does closure work for Ruby's define_singleton_method?
body: <p>This Ruby (2.2.3p173) code:</p>
  
  <pre><code>class A
      def msg
          "hello"
      end
  
      def p
          Proc.new { msg }
      end
  
      def lam
          lambda { msg }
      end
  
      def blk
          (1..3).map { msg }.join(" and ")
      end
  
      def d1(obj)
          obj.define_singleton_method(:say1) { msg }
      end
  
      def d2(obj)
          bound = msg # &lt;== Why is this needed?
          obj.define_singleton_method(:say2) { bound }
      end
  end
  
  a = A.new
  
  puts a.p.call
  
  puts a.lam.call
  
  puts a.blk
  
  obj = Object.new
  
  a.d1(obj)
  
  begin
  # Why does this fail?
  puts obj.say1
  rescue
  puts "caught: #{$!}"
  end
  
  a.d2(obj)
  
  puts obj.say2
  </code></pre>
  
  <p>produces this output:</p>
  
  <pre><code>hello
  hello
  hello and hello and hello
  caught: undefined local variable or method `msg' for #&lt;Object:0x00000001a20638&gt;
  hello
  </code></pre>
  
  <p>What makes the difference in d1 and d2? Why do all of the blocks see msg except for the one passed to define_singleton_method?</p>
  
  <p>Update:</p>
  
  <p>I think it comes down to this:</p>
  
  <blockquote>
    <p>Proc bodies have a lexical scope like functions in Lisp and
    JavaScript, meaning that when Ruby encounters a free variable inside a
    proc body, its value is resolved within the context the proc was
    defined. This is what makes closures possible. Methods are different,
    however. A method's context is the object to which they are bound.
    When Ruby encounters a free variable inside a method body, it assumes
    the variable refers to another method on the object, and this is what
    saves us from having to prefix same-object methods with "this" or
    "self".</p>
  </blockquote>
  
  <p>which I found here: <a href="http://www.joshstaiger.org/archives/2006/12/of_closures_met_1.html" rel="nofollow">Of closures, methods, procs, scope, and Ruby</a>.</p>
  
  <p>All of these various blocks with <code>{ msg }</code> must work as Proc body does. <code>define_singleton_method</code> is taking the block and giving it method's rules.</p>