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
...
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
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
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With