gpt4 book ai didi

ruby - 一个类如何有一个名为 end 的方法

转载 作者:数据小太阳 更新时间:2023-10-29 07:54:47 26 4
gpt4 key购买 nike

在 Sketchup ruby​​ 中,Edge 类有一个名为“end”的方法。

Ruby 如何处理此方法名称以不与标记 blockend 的 protected 关键字冲突(例如 if ... end)?

最佳答案

How does Ruby deal with this method name to not conflict with the protected keyword marking the blockend (eg if … end)?

当使用 def 时,解析器假定后面是一个由圆括号或空格分隔的标识符(一种符号)。您不能使用 def 动态分配方法名称(不使用某种形式的 eval)。

define_method(:end){} 采用符号(或字符串),因此在这里使用保留字也没有问题。

但是不能像在类中通常那样使用隐式接收器调用这些方法:

# ok
class Foo
def end
end

def test
# not ambiguous
self.end
end
end

# syntax error, unexpected keyword_end, expecting end-of-input
class Bar
def end
end

def test
end
end
end

您可以使用显式接收者调用该方法:

Foo.new.end

或者使用动态调用 sendcall .

class Foo
def end
end

def test
send(:end)
method(:end).call
end
end

您还可以在实例 (@end)、类 (@@end) 和全局 ($end) 变量名称中使用关键字,因为印记告诉解析器我们正在处理一个变量,而不是局部变量没有印记。

关于ruby - 一个类如何有一个名为 end 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54200591/

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