Basic tech stuff

Programming and Linux administration

The Ruby module Enumeration is fun

Posted by Daniel Brahneborg on 2007 April 21

In a Ruby application I had a bunch of data in a hash table that I wanted to print in a special format. There were a couple of requirements:

  1. Some of the options should be ignored.
  2. The format should be “key:value”.
  3. The list should be sorted.
  4. The entries should be separated by a space.

Fortunately this sort of thing is dead easy in Ruby, because of all of the cool functions in the Enumeration module. By stacking them after each other, I got this:

KILL_LIST = [ 1, 42, 312 ]
def hash_for_print(hash_data)
    reject {|key, value| KILL_LIST.include?(key)}.
    collect {|key,value| "%03d:%s" % [key, value]}.
    join(" ")

No, it’s not something I’d use in the innermost loop of a realtime system. That’s irrelevant. The code is dead easy to understand and modify, and didn’t take much time to write. Besides, it scales linearly, which is quite important.

Andra bloggar om: , .


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: