gpt4 book ai didi

Ruby 作用域/绑定(bind)

转载 作者:太空宇宙 更新时间:2023-11-03 16:00:26 25 4
gpt4 key购买 nike

以下 Ruby 代码片段的输出

def foo; "foo:function"; end
puts foo
puts foo()
foo = "foo:value"
puts foo
puts foo() # Didn't expect this to work!

foo:function
foo:function
foo:value
foo:function

这很令人费解,我原以为在当前范围内只有一个 foo 绑定(bind),但看起来并非如此。

PS:在 python 中运行等效代码给出了预期的结果(即在将字符串绑定(bind)到 foo 之后,最后一个尝试调用 foo() 的语句给出了错误)。

编辑:

以下是python中的等效示例:

def foo(): return "foo:function"
print foo
print foo()
foo = "foo:value"
print foo
print foo()

产生输出(已编辑):

<function foo at 0x7fb71d912578>
foo:function
foo:value
TypeError: 'str' object is not callable

编辑 2:

因此,在 Ruby 中,与 Python 不同,一个给定的符号可以在同一范围内有两个绑定(bind)(作为方法和作为实例变量)。

最佳答案

尝试在没有括号的情况下输入 foo,您将得到“foo:value”。使用 () 您明确表示这是一种方法。尝试将这两行放在代码的末尾:

puts defined? foo #=> local-variable
puts defined? foo() #=> method

您可能会发现 this SO answer有用,尤其是这部分:

Why does it make sense for local variables to "shadow" methods and not the way around? Well, if methods did shadow local variables, there would no longer be a way to dereference those local variables. However, if local variables shadow methods, then there is still a way to call those methods: remember, the ambiguity only exists for receiverless argumentless methods calls, if you add an explicit receiver or an explicit argument list, you can still call the method:

关于Ruby 作用域/绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26642203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com