Why don't ruby methods have lexical scope?

后端 未结 1 865
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-04 13:28

For example

def test
    a = \"a is for apple\"
    def inner_method
        a = \"something\" # this will refer to a different \"a\"
    end

    inner_method
          


        
相关标签:
1条回答
  • 2021-02-04 13:44

    It's because Ruby's methods aren't first class objects (as they would be in IO, for example). So when you define the inner method, what is the receiver? Presumably the method itself, or the binding or something, but Ruby doesn't have that deep of OO.

    Anyway, it's unclear to me what you were expecting to happen in your example, were you wanting it to modify the local varialbe a? If so, a proc is a suitable substitute for a method.

    def test
      a = "a is for apple"
      inner_method = lambda do
        a = "something"
      end
    
      a # => "a is for apple"
      inner_method.call
      a # => "something"
    end
    
    test
    

    "functional.rb" is a more extravagant example of this style of programming.

    And "lambda, proc, and Proc.new" is a breakdown of Ruby's different types of closures.

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