Last active
December 18, 2015 00:09
-
-
Save crazymykl/5694222 to your computer and use it in GitHub Desktop.
FizzBuzz, lambda edition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /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