Baby's first FizzBuzz

Pardon the inane post content, I'm just trying out the code highlighting and blockquote styles I've been working on.

I interviewed a while ago for a Ruby on Rails position, which was actually my first ever Rails interview. The first technical question they gave me was a standard FizzBuzz-style question:

Iterate over the integers from 1 to 100 inclusive. For each integer: if the integer is evenly divisible by 3, print "foo"; if the integer is evenly divisible by 5, print "bar"; if the integer is evenly divisible by 7, print "baz"; otherwise, print just the number.

I asked the usual clarifying questions (what to do if the number is divisible by both 3 and 5, etc.) and got to work. I also found it interesting that the problem domain stopped before 105, the first number evenly divisibly by each of 3, 5, and 7. My first attempt in Ruby looked like this:

(1..100).each do |i|
  puts "foo" if i % 3 == 0
  puts "bar" if i % 5 == 0
  puts "baz" if i % 7 == 0
  puts i unless
    (i % 3 == 0) ||
    (i % 5 == 0) ||
    (i % 7 == 0)
end

Yikes. It works, but I commented right away that it was unRubyish and pretty ugly overall. The interviewers agreed, but balked when I offered to make it look better. Instead, they asked me to print every string about a given number on one line, such that there were 100 lines of output. Unfortunately, I momentarily forgot about print. D'oh:

(1..100).each do |i|
  out = ""
  out << "foo" if i % 3 == 0
  out << "bar" if i % 5 == 0
  out << "baz" if i % 7 == 0
  out << "#{i}" unless
    (i % 3 == 0) ||
    (i % 5 == 0) ||
    (i % 7 == 0)
  puts out
end

Here I tripped up the interviewer: he asked me to explain why I appended an interpolated string ("#{i}") rather than just the integer. He said that shoveling (<<) a non-string onto a string included an implied #to_s call on the object, but I thought that the behavior might be not be so expected. It turns out that shoveling an integer onto a string appends the equivalent of i.chr to the string, so "FOOBA" << 82 yields "FOOBAR" rather than "FOOBA82". Even while writing this up, I've spotted several more areas ripe for self-criticism, but I'll refrain from boring any of you for much longer.

Here I had read about how so many interviewees bomb the FizzBuzz test, and I thought "That could never happen to me!" But it turns out under the pressure of the interview, I produced code that was far worse than I'm normally capable of. I did OK, certainly not spectacularly, on the real technical questions, but the experience overall was very helpful. Next time I have a Rails interview, I'll know how to better prepare myself.

blog comments powered by Disqus