如何根据具体数字制作序列?

时间:2012-10-31 10:00:11

标签: ruby

如何从平方码的开头创建序列,然后将其添加到上一个结果?

7 => 49, 56, 63, ...

def make_sequence(number)
  lambda { number*number ??? }
end

num = make_sequence(7)
num.call #=> 49
num.call #=> 56
...

3 个答案:

答案 0 :(得分:3)

按照你最初的想法使用闭包我写道:

def make_sequence(n)
  x = n**2 - n
  lambda { x += n }
end

num = make_sequence(7)
p num.call #=> 49
p num.call #=> 56

答案 1 :(得分:2)

使用Enumerator

def make_sequence(start)
  pos = start**2
  Enumerator.new do |y|
    loop do
      y.yield(pos)
      pos += start
    end
  end
end

seq = make_sequence(7)
seq.next   #=> 49
seq.next   #=> 56

...

答案 2 :(得分:2)

Fiber版本:

def make_sequence(num)
  inc = num
  num = num*num
  Fiber.new do
    loop do
      Fiber.yield(num)
      num += inc
    end
  end
end

a = make_sequence(7)
p a.resume  #=> 49
p a.resume  #=> 56
p a.resume  #=> 63
...