Skip to content

Instantly share code, notes, and snippets.

@Kerrick
Created April 24, 2012 20:36
Show Gist options
  • Select an option

  • Save Kerrick/2483510 to your computer and use it in GitHub Desktop.

Select an option

Save Kerrick/2483510 to your computer and use it in GitHub Desktop.
Different solutions for Fizz Buzz in Ruby
def fizz_buzz_1(max)
arr = []
(1..max).each do |n|
if ((n % 3 == 0) && (n % 5 == 0))
arr << "FizzBuzz"
elsif (n % 3 == 0)
arr << "Fizz"
elsif (n % 5 == 0)
arr << "Buzz"
else
arr << n
end
end
return arr
end
def fizz_buzz_2(max)
arr = []
(1..max).each do |n|
if (n % 3 == 0)
if (n % 5 == 0)
arr << "FizzBuzz"
else
arr << "Fizz"
end
elsif (n % 5 == 0)
arr << "Buzz"
else
arr << n
end
end
return arr
end
def fizz_buzz_3(max)
arr = []
(1..max).each do |n|
text = ""
if (n % 3 == 0)
text << "Fizz"
end
if (n % 5 == 0)
text << "Buzz"
end
if !((n % 3 == 0) || (n % 5 == 0))
text = n
end
arr << text
end
return arr
end
@alaa-alawi
Copy link

alaa-alawi commented May 23, 2025

for n in 1..101
  print "Fizz" if n%3 == 0
  print "Buzz" if n%5 == 0
  print n unless n%3 == 0 || n%5 == 0
  print "\n"
end

@RillonDodgers
Copy link

(1..100).each_with_object([]) do |number, array|
  next array << "FizzBuzz" if number % 15 == 0
  next array << "Fizz" if number % 3 == 0
  next array << "Buzz" if number % 5 == 0

  array << number
end

@Kerrick
Copy link
Author

Kerrick commented Nov 14, 2025

Fizz Buzz, Object-Oriented Edition

module NumericRefinements
  refine Numeric do
    def divisible_by?(other) = remainder(other).zero?
  end
end
class Replacement
  def self.for(n) = @registered.find { it.valid? n }.new(n).to_s
  def initialize(n) = @n = n

  def self.valid?(n) = false
  def to_s = self.class.name
 
  private
  # Subclasses defined later take precedence
  def self.register(subclass) = (@registered ||= []).prepend subclass
  def self.inherited(subclass) = register subclass
end
using NumericRefinements
 
class TheNumber < Replacement
  def self.valid?(n) = true
  def to_s = @n.to_s
end
 
class Fizz < Replacement
  def self.valid?(n) = n.divisible_by?(3)
end
 
class Buzz < Replacement
  def self.valid?(n) = n.divisible_by?(5)
end
 
class FizzBuzz < Replacement
  def self.valid?(n) = Fizz.valid?(n) && Buzz.valid?(n)
end
class Game
  def initialize(limit: 16) = @limit = limit
  def to_a = (1..@limit).collect { Replacement.for it }
end
 
puts Game.new.to_a

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment