RSS-feed

Fri, 24 Oct 2008

Ruby-talk gems


I came across these bits while going over ruby-talk:

class A < Struct.new(:a, :b)
 def initialize(h)
   # . (*self.class.members.map {|s| s.intern}
   #    self is A, but A extends Struct. .members return an array with
   #    all the names of the instance variables. We iterate over them with map
   #    and then we we call .intern to return the :symbol of it.
   #
   super *h.values_at(*self.class.members.map {|s| s.intern})
 end
end

a = A.new(:a => 1, :b => 2)
p a 

It is a very nice way to extend Struct so you instantiate the class by passing a Hash with attributes and values that you want to store in the struct.

That sort of inspired me to write this to help another developer:

# input.txt
# c,d,a,b
# 3,4,1,2

# Read first line and order the input
l1 = File.open("./input.txt", "r").read.split[1].split(',')

# Create a struct class to hold the stats per lane
line_stats = Struct.new(:c, :d, :a, :b)
# Instantiate a stat lines with the input data
l1_stats = line_stats.new(*l1)

# Display the contents of the struct
puts l1_stats.inspect

To get an idea about the domain of the problem. We want here to parse a csv file, store the entries in memory and then call a perl script using those values. There are a couple of things I would highlight about that code. First of all, the nice way we can tell a ruby method that we are sending the arguments in an array. Also, the Struct class fits right in and avoid a bunch of lines of code.

posted at: 23:32 | path: /ruby | permanent link to this entry