Skip to content

Instantly share code, notes, and snippets.

@cheeyeo
Created March 20, 2014 20:10
Show Gist options
  • Save cheeyeo/9672761 to your computer and use it in GitHub Desktop.
Save cheeyeo/9672761 to your computer and use it in GitHub Desktop.
Ruby hash selector pattern
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