Basic tech stuff

Programming and Linux administration

Archive for April, 2007

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: , .

Posted in programming, ruby | Leave a Comment »

32 bit IP address to dotted notation in Ruby

Posted by Daniel Brahneborg on 2007 April 13

In one of our applications we store an IP address as a 32 bit integer. To show the value of this field it must be converted to normal dotted notation, and then back again to an integer to get stored in the database.

Going from dotted notation is easy:

require 'ipaddr'
IPAddr.new('1.2.3.4').to_i

Or, the “manual” version:

'1.2.3.4'.split('.').inject(0) {|total,value| (total << 8 ) + value.to_i}

I couldn’t find any examples of going from an integer to dotted notation, so I ended up with this:

address = 0x01020304
[24, 16, 8, 0].collect {|b| (address >> b) & 255}.join('.')

Andra bloggar om: , .

Posted in programming, ruby | 7 Comments »