today's rubyism - enumerables

One of the things I quite like about ruby is the number of useful methods you get for free with common data types.

I discovered a new one today which every class that mixes in Enumerable can use: each_with_index. I was generating lists of IP addresses with the Range type for the last octet and started out using an offset so the server number mapped to the IP address (the servers start at ‘001’ but the first available IP was 31):



r = 31..40

r.each do |i|

    svr = "myserver%03d" % (i - 30)   # printf style syntax for zero-padded hosts

    puts "10.10.20.#{i}\t#{svr}"

end



10.10.20.31 myserver001

10.10.20.32 myserver002 [ … ]

But I had to iterate over this several times with different sets of IP ranges, and remembering to subtract the right number from the IP address to end up with the first server at 1 was bringin’ me down. So I looked at the above-linked docs for the Enumerable class thinking there was probably something clever you could do with the ‘each’ method, and sure enough:

enum.each_with_index {|obj, i| block } → enum
Calls block with two arguments, the item and its index, for each item in enum.

So the code became:




r = 31..40

r.each_with_index do |i, x|

    svr = "myserver%03d" % (x + 1)   # indexes start at zero   

    puts "10.10.20.#{i}\t#{svr}"

end



Just one of the ways ruby makes my life a little better.

Published: August 03 2010

  • category:
  • tags: