Ruby的yield
关键字与同名的Python关键字有很大不同,所以不要被它搞混了.Ruby的yield
关键字是用于调用与方法关联的块的语法糖.
最接近的类似功能是Ruby的枚举器类.例如,Python的类似功能:
def eternal_sequence():
i = 0
while True:
yield i
i += 1
这是:
def eternal_sequence
Enumerator.new do |enum|
i = 0
while true
enum.yield i # <- Notice that this is the yield method of the enumerator, not the yield keyword
i +=1
end
end
end
还可以使用enum_for
为现有枚举方法创建枚举数.例如,('a'..'z').enum_for(:each_with_index)
为您提供了一个小写字母的枚举器,以及它们在字母表中的位置.使用标准的可枚举方法(如1.9中的each_with_index
)可以免费获得这个结果,因此只需编写('a'..'z').each_with_index
即可获得枚举数.