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)
  hash_data.
    reject {|key, value| KILL_LIST.include?(key)}.
    collect {|key,value| "%03d:%s" % [key, value]}.
    sort.
    join(" ")
end

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

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>