为什么ruby方法没有词法作用域? [英] Why don't ruby methods have lexical scope?

查看:96
本文介绍了为什么ruby方法没有词法作用域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如

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?

推荐答案

这是因为Ruby的方法不是第一类对象(因为它们在 IO )。所以当你定义内部方法,什么是接收器?大概是方法本身,或绑定或某事,但是Ruby没有那么深的OO。

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.

无论如何,我不知道你期望发生什么你的例子,你想要修改本地varialbe a ?如果是这样,proc是一个合适的替代方法。

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 是这种编程风格的更奢侈的例子。

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

lambda,proc和Proc.new 是Ruby的不同类型的闭包的细分。

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

这篇关于为什么ruby方法没有词法作用域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆