Why don't ruby methods have lexical scope?

馋奶兔 提交于 2019-12-31 13:57:51

问题


For example

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

    inner_method
    puts a
end

Are there any reasons for this? Blocks have lexical scope, so why don't methods? Is this going to be fixed?


回答1:


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.



来源:https://stackoverflow.com/questions/9089414/why-dont-ruby-methods-have-lexical-scope

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!