HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

FizzBuzz from a casual rubyist

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
fromrubyistcasualfizzbuzz

Problem

As a casual Rubyist I am mainly interested, how ideomatic my solution is.

class Integer
  def divisible_by?(n)
    (self % n).zero?
  end
end

def fizzbuzz(upper_bound)
  1.upto(upper_bound).map do |number| 
    next "fizzbuzz" if number.divisible_by? 3 and number.divisible_by? 5
    next "fizz" if number.divisible_by? 3
    next "buzz" if number.divisible_by? 5
    next number
  end
end

puts fizzbuzz 100


Remarks: I borrowed the idea for monkeypatching Integer from @tokland here

Solution

If you're aiming for readability rather than efficiency or maintainability — and that is a reasonable tradeoff for FizzBuzz — then I would say "Well done." (You could test for divisibility by 15 for efficiency and avoid monkey-patching for maintainability.)

Conventionally, the output should be one entry per line, rather than an array.

If you're going to take an upper bound as a parameter, you may as well take a range, and the parameter should default to 1..100.

Therefore, a better way to call the code would be

fizzbuzz(1..100).each { |output| puts output }


or, using the default,

fizzbuzz.each { |output| puts output }

Code Snippets

fizzbuzz(1..100).each { |output| puts output }
fizzbuzz.each { |output| puts output }

Context

StackExchange Code Review Q#74996, answer score: 6

Revisions (0)

No revisions yet.