Created
March 20, 2014 20:10
-
-
Save cheeyeo/9672761 to your computer and use it in GitHub Desktop.
Ruby hash selector pattern
This file contains hidden or 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
class Fizzbuzz | |
def initialize(number) | |
@number = number | |
end | |
def self.count(number) | |
count = new(number) | |
count.output_data[count.selector.to_s] | |
end | |
def self.count_if(number) | |
count = new(number) | |
count.output_if | |
end | |
def output_if | |
result = 'Fizz' if @number % 3 == 0 | |
result = 'Buzz' if @number % 5 == 0 | |
result = 'Fizzbuzz' if @number % 15 == 0 | |
result | |
end | |
def output_data | |
{ "3" => "Fizz", | |
"5" => "Buzz", | |
"15" => "Fizzbuzz" } | |
end | |
def selector | |
output_data.keys.map { |k| k.to_i }.select do |k| | |
@number % k == 0 | |
end.last | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment