Introduction to Array and Hash Methods

One significant programming paradigm I first learned with perl, and have carried over to other programming languages such as ruby, is to think of arrays and hashes as fundamental data types, accompanied by their associated functions/methods. Though not as great of a leap as the transition from procedural to object-oriented programming; to be able to work and think fluidly, and write succinct code using arrays and hashes is an important programming skill to have. Once one develops this habit, to work in a language in which these methods are lacking feels similar to speaking in a foreign language that lacks words for the ideas you want to express. In programming, properly using these methods effectively translates into less lines of code and/or greater abstraction.

A basic example is taking an array of numbers

list = [ 1, 2, 3, 4, 5 ]

and squaring them:

squares = list.map { |x| x*x }

Without using an array function like map, we are forced to iterate:

squares = Array.new( list.size )
list.each_index do |i| # put for loop here
  squares[i] = list[i] * list[i]
end
# squares
[1, 4, 9, 16, 25]

Note the relative clarity and brevity of using map to calculate the squares.

For an example that is less trivial, say we have a hash that we want to url-encode and put into an HTTP GET query string.

hash = { 'Name' => 'Dave Bowman', 'Ship' => 'Discovery One' }

Using a traditional iterative method that can be directly translated into most modern languages:

require 'cgi'
class Hash
  def urlencode
    output = ''
    each do |name,value|
      output += '&' if !output.empty?
      output += CGI.escape(name.to_s) +'='+ CGI.escape(value.to_s)
    end
    output
  end
end

Here we take advantage of ruby’s open class definitions, so that we define urlencode to be a method of the built-in Hash class.

We can accomplish the same thing using array methods map and join:

require 'cgi'
class Hash
  def urlencode
    to_a.map do |name_value|
      name_value.map { |e| CGI.escape e.to_s }.join '='
    end.join '&'
  end
end

The to_a Hash method returns the hash as an array of name,value pairs:

# hash.to_a
[["Name", "Dave Bowman"], ["Ship", "Discovery One"]]

Both of these methods return hash.urlencode as

# hash.urlencode
"Name=Dave+Bowman&Ship=Discovery+One"

however the second method more clearly uses the ‘&’ character for what it is: it joins the name=value pairs together, which is not as evident in the first method definition.

If you are not already familiar with these array/hash methods, hopefully this article has provided a brief introduction to them. The next time you need to transform an array or hash in a uniform manner, rather than iterating through them, you might consider experimenting with these types of methods.

Share:
  • del.icio.us
  • Reddit
  • Technorati
  • Twitter
  • Facebook
  • Google Bookmarks
  • HackerNews
  • PDF
  • RSS
This entry was posted in programming. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.