Ruby中是否有类似Python生成器的东西? [英] Are there something like Python generators in Ruby?

查看:64
本文介绍了Ruby中是否有类似Python生成器的东西?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Ruby的新手,有没有办法从Ruby函数中获取yield值?如果是,怎么办?如果没有,我编写懒代码的选择是什么?

I am new to Ruby, is there a way to yield values from Ruby functions? If yes, how? If not, what are my options to write lazy code?

推荐答案

Ruby的yield关键字与同名的Python关键字有很大不同,因此请不要混淆. Ruby的yield关键字是语法糖,用于调用与方法关联的块.

Ruby's yield keyword is something very different from the Python keyword with the same name, so don't be confused by it. Ruby's yield keyword is syntactic sugar for calling a block associated with a method.

最接近的等效项是Ruby的Enumerator类.例如,等效于Python:

The closest equivalent is Ruby's Enumerator class. For example, the equivalent of the 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等标准Enumerable方法免费获得此代码,因此只需编写('a'..'z').each_with_index即可获取枚举数.

You can also create Enumerators for existing enumeration methods with enum_for. For example, ('a'..'z').enum_for(:each_with_index) gives you an enumerator of the lowercase letters along with their place in the alphabet. You get this for free with the standard Enumerable methods like each_with_index in 1.9, so you can just write ('a'..'z').each_with_index to get the enumerator.

这篇关于Ruby中是否有类似Python生成器的东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆