Skip to content

Instantly share code, notes, and snippets.

@crazymykl
Last active December 18, 2015 00:09
Show Gist options
  • Save crazymykl/5694222 to your computer and use it in GitHub Desktop.
Save crazymykl/5694222 to your computer and use it in GitHub Desktop.
FizzBuzz, lambda edition
#! /usr/bin/env ruby
class FizzBuzz
attr_reader :limit, :matchers
DEFAULT_LIMIT = 100
DEFAULT_MATCHERS = [
-> x { "Fizz" if (x % 3).zero? },
-> x { "Buzz" if (x % 5).zero? },
]
def initialize limit=DEFAULT_LIMIT, matchers=DEFAULT_MATCHERS
raise ArgumentError, "Limit must be a positive integer!" if limit < 1
@limit = limit
@matchers = matchers
self.(1)
end
def call i
return if i > limit
matches = matchers.map { |p| p.(i) }.compact
puts matches.empty? ? i.to_s : matches.join
self.(i+1)
end
def self.[] i=nil
new (i || DEFAULT_LIMIT).to_i
end
end
def fizzbuzz i=nil
FizzBuzz[i]
end
fizzbuzz ARGV[0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment