0 1 2 3 4 5 6 7 8 9 我知道 times 重复一-6ren">
gpt4 book ai didi

ruby - 这个输出是如何实现的?

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

我是 Ruby 新手。我在阅读教程时发现了这段代码

10.times { |i | print i, " " } # o/p => 0 1 2 3 4 5 6 7 8 9  

我知道 times 重复一个 Action 被调用的次数。我假设我被初始化为 0。但是,它是如何增加的?

最佳答案

I assume that i gets initialised to 0. But, how it's getting incremented?

有一个内部变量,整数本身不会改变。让我们使用基本的 while 循环来实现我们自己的 times 方法:

class Integer
def my_times
i = 0 # initialize to 0
while i < self # self is the integer object, i.e. 10
yield i # pass i to the block
i += 1 # increment i
end
end
end

用法:

10.my_times { |i| print i, " " } #=> 0 1 2 3 4 5 6 7 8 9

Ruby 方法更复杂(返回没有 block 的枚举器),但您明白了。

关于ruby - 这个输出是如何实现的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28429702/

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