class Fibonacci::Fibonacci

This class encapsulates functionality retalted to the generation of Fibonacci sequences.

Public Class Methods

sequence(count) → array click to toggle source
sequence(count) {|val| ... } → nil

Calculate the first count Fibonacci numbers, starting with 1,1.

If a block is given, supply successive values to the block and return nil, otherwise return all values as an array.

# File lib/fibonacci/fibonacci.rb, line 15
def self.sequence(count, &block)
    result, block = setup_optional_block(block)
    generate do |val|
        break if count <= 0
        count -= 1
        block[val]
    end
    result
end
upto(max) → array click to toggle source
upto(max) {|val| ... } → nil

Calculate the Fibonacci numbers up to and including max.

If a block is given, supply successive values to the block and return nil, otherwise return all values as an array.

# File lib/fibonacci/fibonacci.rb, line 33
def self.upto(max, &block)
    result, block = setup_optional_block(block)
    generate do |val|
        break if val > max
        block[val]
    end
    result
end

Private Class Methods

generate() { |f1| ... } click to toggle source

Yield a sequence of Fibonacci numbers to a block.

# File lib/fibonacci/fibonacci.rb, line 45
def self.generate
    f1, f2 = 1, 1
    loop do
        yield f1
        f1, f2 = f2, f1 + f2
    end
end
setup_optional_block(block) click to toggle source

If a block parameter is given, use it, otherwise accumulate into an array. Return the result value and the block to use.

# File lib/fibonacci/fibonacci.rb, line 55
def self.setup_optional_block(block)
    if block.nil?
        [ result = [], lambda { |val| result << val } ]
    else
        [ nil, block ]
    end
end