Reputation: 21791
How to make sequence from the beginning of square number and then adding it to the previous result?
7 => 49, 56, 63, ...
def make_sequence(number)
lambda { number*number ??? }
end
num = make_sequence(7)
num.call #=> 49
num.call #=> 56
...
Upvotes: 3
Views: 81
Reputation: 67850
Following your initial idea using closures I'd write:
def make_sequence(n)
x = n**2 - n
lambda { x += n }
end
num = make_sequence(7)
p num.call #=> 49
p num.call #=> 56
Upvotes: 3
Reputation: 10107
A Fiber version:
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
...
Upvotes: 2
Reputation: 5949
use 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
...
Upvotes: 2