Colin's Ruby Quiz #126 Submission 3

Posted by Colin A. Bartlett Sun, 03 Jun 2007 13:03:00 GMT

If you haven’t looked at this week’s RubyQuiz yet, beware. Spoilers ahead.

This week’s quiz was dead simple. But I think that’s the point of this one. The most interesting thing about RubyQuiz for me is looking at how other people solved the same problem (no matter how simple) and learning about other ways to do things.

Here’s my solution:

(1..100).each do |n|
  ret = ""
  ret += "Fizz" if n.divmod(3).last == 0
  ret += "Buzz" if n.divmod(5).last == 0
  ret = n if ret == ""
  puts ret
end

The challenge presented this week is one that is well suited for a quick in-interview coding session for potential hires. Having prospective employees write code was a new idea to me that I read about in Joel on Software. And although I didn’t have candidates in the last round of hiring write code, I did review some psudo-code on the whiteboard with them and I think the next candidates will actually sit down at a machine and tap something out for us in our presence.

Trackbacks

Use the following link to trackback from your own site:
http://blog.kineticweb.com/articles/trackback/37

Comments

Leave a response

  1. Avatar
    AlSquire about 2 hours later:
    I would have used the % operator for modulo ( if n % 3 == 0 ).
  2. Avatar
    AlSquire about 3 hours later:
    A one line and not very readable way :
    puts (1..100).map { |i| (ret = { "Fizz" => 3, "Buzz" => 5 }.map { |w, m| w if i % m == 0 }.join) == "" ? i : ret }
  3. Avatar
    Mat Schaffer about 8 hours later:
    I like this one much better:

    1.upto(?d){|i,x|i%3<1&&x=:Fizz;puts i%5<1?"#{x}Buzz":x||i}

    courtesy of
    http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/241505

    (No I don't really think you should do this in an interview, but I love the absurdity of it :) ).
Comments