覆盖“for” Ruby 中的关键字。是否可以?
我四处搜索并尝试覆盖“for”关键字,但我什么也没找到。 我正在尝试类似的事情:
def for("maybe_arguments_go_here")
print "Hello from function for!"
end
for i in 1..3
print "Hello from for"
end
I search around and tried overriding the "for" keyword but I found nothing.
I am trying something like that:
def for("maybe_arguments_go_here")
print "Hello from function for!"
end
for i in 1..3
print "Hello from for"
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不能覆盖关键字本身,但您可以做的一件事是说明
for
对您自己的类执行的操作。for
在内部调用each
,因此以下技巧将起作用:You can't override the keyword itself, but one thing you can do is say what
for
does for your own classes.for
callseach
internally, so the following trick will work:我不认为“覆盖”关键字在任何语言中都是一个选项,您只能覆盖方法和运算符(运算符本身是现代语言中的方法),
for
是 Ruby 中的关键字。但是您仍然可以执行以下操作:I don't think that 'overriding' a keyword is an option at any language, you can override methods and operators(operators themselves are methods in modern languages) only,
for
is a keyword in Ruby. However you still can do things like the following:如果你给这个方法一个显式的接收者,它会起作用,但是如果你没有显式地将 self 放在它前面,你将无法使用该方法。
这会起作用:
或者
但是,我同意 khell 和上面的一些评论,即重新定义关键字是一个巨大的不,当然,如果我们只是尝试并享受乐趣,那就去做吧!
If you give the method an explicit receiver it would work, but you would not be able to use the method without explicitly putting self before it.
This would work:
OR
BUT, I agree with khell and some of the comments above that redefining keywords is a massive no no, of course, if we're just experimenting and having fun, then go for it!