I've been wanting to do a
Ruby Quiz now for quite some time, but I've always had some excuse about being too busy. But this week's Ruby Quiz is
FizzBuzz, so I had to take the two minutes and write up a solution.
Some of the discussion on
Ruby Talk has been around getting the smallest solution possible (even though the quiz directs us to do as we might for a job interview). There are plenty of claims ranging from 56 to 72 bytes. I couldn't even get under 100, so I'm quite interested to see the different solutions when they are published - not because I think code so terse as to be unintelligible is something we should strive for, but because surely I'll learn new tricks (and some of which I'd expect are understandable!).
Anyway, here's my Ruby FizzBuzz (how exciting):
class Integer
def fizzbuzz
fizzable = self % 3 == 0
buzzable = self % 5 == 0
print "Fizz" if fizzable
print "Buzz" if buzzable
print self if !(fizzable || buzzable)
puts
end
end
(1..100).each {|i| i.fizzbuzz}
The one part where I did learn something was that
self
gets me the member variable holding the integer here. I didn't know that before, and I started out looking for "how to find the name of the member variable in Ruby Integer class" (or some such search query). When I didn't find anything, I thought I'd try the obvious -
self
. Of course, like many things in Ruby, it followed the principle of least surprise, and my guess worked.
Hey! Why don't you make your life easier and subscribe to the full post
or short blurb RSS feed? I'm so confident you'll love my smelly pasta plate
wisdom that I'm offering a no-strings-attached, lifetime money back guarantee!
Leave a comment
You know, I was thinking a better implementation would be for Integer#fizzbuzz to return a string, and instead puts i.fizzbuzz in the loop. That would certainly shave off many characters, and more importantly make the program have a better design (in my opinion).
Posted by
Sam
on Jun 02, 2007 at 06:46 PM UTC - 6 hrs
I got it down to 96 characters with this beast, so I'm guessing to shave another 20 off of that (and 40 for the best claim), I'd need to drastically change my approach:
def z i;r="";r+="Fizz" if i%3==0;r+="Buzz" if i%5==0;r=i if r=="";r;end;1.upto(100){|i|puts z i}
Posted by
Sam
on Jun 02, 2007 at 07:06 PM UTC - 6 hrs
So, the main idea that removed the bytes was the ternary operator. I abhor trying to figure code like that out, so I didn't even think to use it. =) Lesson learned, and next time I go golfing (see
http://codegolf.com/) I'll be sure to have it in my toolkit.
Posted by
Sammy Larbi
on Jun 04, 2007 at 09:30 AM UTC - 6 hrs
Leave a comment