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
and squaring them:
Without using an array function like map, we are forced to iterate:
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.
Using a traditional iterative method that can be directly translated into most modern languages:
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:
The to_a Hash method returns the hash as an array of name,value pairs:
Both of these methods return hash.urlencode as
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.
No Comments, Comment or Ping
Reply to “Introduction to Array and Hash Methods”