Are there something like Python generators in Ruby?

后端 未结 4 900
遇见更好的自我
遇见更好的自我 2020-12-13 09:09

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?

4条回答
  •  醉梦人生
    2020-12-13 09:56

    Ruby supports generators out of the box using Enumerable::Generator:

    require 'generator'
    
    # Generator from an Enumerable object
    g = Generator.new(['A', 'B', 'C', 'Z'])
    
    while g.next?
      puts g.next
    end
    
    # Generator from a block
    g = Generator.new { |g|
      for i in 'A'..'C'
        g.yield i
      end
    
      g.yield 'Z'
    }
    
    # The same result as above
    while g.next?
      puts g.next
    end
    

    https://ruby-doc.org/stdlib-1.8.7/libdoc/generator/rdoc/Generator.html

提交回复
热议问题