FizzBuzz 2

I want to compare now my Ruby FizzBuzz code with two others I found on the web.

This is mine:

Not bad, not bad.

I was curious to see what other solutions was possible with Ruby. So I decided to research in the series of tubes.

I found this one interesting:

and also this:

These two examples I found on the internet are great because they put in practice an important best practice in programming called DRY or Don’t Repeat Yourself.

In the first one, there is only a single call to puts(), and the results of the modulo 3 and 5 cached in variables. A major enhancement from my code for instance. I also liked the (1..100).each bit. Different from the loop that I used. I did not know you could use .each methods with range in such manner.

The second internet example is mind-blowing. The code does not repeat itself at all. This blogger explains what it does very well:

“A divisible by three check adds the ‘Fizz’ and divisible by five the ‘Buzz’ If the number happens to be divisible by both they will be combined to yield ‘FizzBuzz’ From there, a quick check is needed to see if the String is still empty?(), meaning that we should output the digit instead.”

Succinct and beautiful. Very well, very well.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s