作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
在 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
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/
我是一名优秀的程序员,十分优秀!