Solving the Fizzbuzz Puzzle with Ruby

So back in February Jeff Atwood over at codinghorror.com was talking about a puzzle to give prospective new-hires when interviewing them entitled “Fizzbuzz”. You can read more about it here.

So with a little thought I decided to solve the fizzbuzz puzzle using Rudy and an Array.

count = 0
100.times do
  count += 1
  fb = []
  fb << "Fizz" if (count % 3) == 0
  fb << "Buzz" if (count % 5) == 0
  fb << count if (count % 3) != 0 and (count % 5) != 0
  puts (fb.join "")
end

For those of you that are curious as to why I used a local variable of count rather then the index identifier, is because the article by Jeff Atwood requests a loop from 1-100 and Ruby starts looping at 0.


Random Testimonials with Rails

A common functionality seen on many websites is to display a random testimonial from a client or customer of your product on a side bar or within the masthead, doing this in Rails is quite simple and is done with the assistance of a Rails helper and rendering a partial.

First off course you are going to need to generate your model within your command prompt/terminal insuring that you are in your projects directory:

script/generate model Testimonial

I’m expecting here that you are familiar enough with rails to create the migration file yourself and add a field for both the testimonial itself as well as the signature. Note Rails currently at 1.2.3 has an issue when using the name “quote” for a column name in your table.

Next let’s code the helper. In our helpers folder let’s open the application_helper.rb and add the following:

def show_random_testimonial
  @random_testimonial = Testimonial.find(:first, :order => 'RAND()')
  render(:partial => 'shared/random_testimonial', :object => @random_testimonial)
end

I like to put all my partials in a separate subdirectory in my views called shared.

Alright, so now create that shared directory in the view directory and create the file _random_testimonial.rhtml to use as our partial. Here we go:

<blockquote>
  <p><%= random_testimonial.statement %></p>
  <cite><%= random_testimonial.signature %></cite>
</blockquote>

You’ll notice above that I called my column for the testimonial itself “statement” which is a text field, and “signature” for the customer’s name which is a string/varchar. Now all you have to do is open up your layout file and call the helper <%= show_random_testimonial %> wherever you want your random testimonial to appear.

So that’s it. Until next time.


Follow

Get every new post delivered to your Inbox.