Ruby 做题:Custom Enumerators - Fibonacci

chenge · 2014年04月25日 · 最后由 chenge 回复于 2014年04月25日 · 1494 次阅读

5yku 难度

Ruby has very powerful enumerator support, including the ability to create your own custom enumerators on the fly.

digits = Enumerator.new do |y|
  i = 0
  loop do
    y.yield i
    i += 1
  end
end

digits.next # => 0
digits.next # => 1

digits.take_while {|n| n < 13} # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Create an enumerator "fib" that outputs successive fibonacci numbers.

For example:

fib.next # => 1
fib.next # => 1
fib.next # => 2

fib.take_while {|n| n < 100} # => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
fib = Enumerator.new do |y|
  i, j = 1, 1
  loop do
    y.yield i
    i, j = j, i + j
  end
end

#1 楼 @blacktulip 能否解释一下,不是很懂 y.yield。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号