gpt4 book ai didi

ruby - 在 Ruby 中覆盖 "for"关键字。是否可以?

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

我四处搜索并尝试覆盖“for”关键字,但我一无所获。我正在尝试这样的事情:

def for("maybe_arguments_go_here")
print "Hello from function for!"
end

for i in 1..3
print "Hello from for"
end

最佳答案

您不能覆盖关键字本身,但您可以做的一件事是说明 for 对您自己的类做了什么。 for 在内部调用 each,所以下面的技巧会起作用:

class MyFor
def initialize(iterable)
@iterable = iterable
end

def each
@iterable.each do |x|
puts "hello from for!"
yield x
end
end
end

# convenient constructor
module Kernel
def my(x)
MyFor.new(x)
end
end

for i in my(1..3)
puts "my for yielded #{x}"
end

关于ruby - 在 Ruby 中覆盖 "for"关键字。是否可以?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1852057/

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