Skip to content

Instantly share code, notes, and snippets.

@ivandenysov
Last active May 20, 2018 14:28
Show Gist options
  • Save ivandenysov/afdd38df10e1ca999c0af777695e36a1 to your computer and use it in GitHub Desktop.
Save ivandenysov/afdd38df10e1ca999c0af777695e36a1 to your computer and use it in GitHub Desktop.
Even Fibonacci Numbers
class FibonacciSequence
DEFAULT_MAX = 4_000_000
DEFAULT_FILTER_BY = :even?
def initialize(max: DEFAULT_MAX, filter_by: DEFAULT_FILTER_BY)
@max = max
@filter_by = filter_by
validate_arguments
@enumerator = build_enumerator
end
def sum
to_a.reduce(&:+)
end
def to_a
@enumerator.to_a
end
private
def validate_arguments
raise(ArgumentError, "max must be a Numeric.") unless @max.is_a?(Numeric)
unless @filter_by.is_a?(String) || @filter_by.is_a?(Symbol)
raise(ArgumentError, "filter_by must be a String or a Symbol.")
end
end
def build_enumerator
Enumerator.new do |yielder|
previous = 1
following = 2
yielder << previous if previous.send(@filter_by)
yielder << following if following.send(@filter_by)
loop do
previous, following = following, previous + following
next unless following.send(@filter_by)
break if following > @max
yielder << following
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment