All programmers use them. You might call them Maps, Dictionaries, Hash Maps, or Associative Arrays. In the Ruby world, we call them Hashes and they're pretty awesome. A Hash is, simply put, a collection of key-value pairs. It is similar to an Array, except that it is indexed via arbitrary keys of any object type instead of an incremental integer. If you take a look at the Hash API, you'll see that it offers an impressive range of functionality. In this article, we won't be looking at the Hash API as such, but rather at using Hashes to model, abstract, and solve common logic problems.
Truth Tables and Capturing the Algorithm
Many people use Hashes purely as simple data lookup tables or as named parameters to methods. This is all fine, but we can do much more by leveraging Hash's inherent flexibility and powerful features to implement logic and complex algorithms. Let's look at an interviewer's favorite, the FizzBuzz test. It goes like this:
"Write a program that prints the numbers from 1 to 100. For multiples of 3, print “Fizz” instead of the number and for multiples of 5, print “Buzz”. For numbers which are multiples of both 3 and 5, print “FizzBuzz”."
We have two conditions here which affect the outcome: (n % 3 == 0
) and (n % 5 == 0
). As soon as we grok that, solving the problem is straightforward:
To run FizzBuzz for a sequence of 1 to 100 we do:
[ruby] (1..100).each {|n| puts conditional(n)} [/ruby]Continue reading %Algorithmic Fun with Ruby Hashes%
by Fred Heath via SitePoint
No comments:
Post a Comment