May 1, 2008

A block in Ruby is an expression delimited by braces that has, to try to put it simple, no life by itself. Thus if we write:

irb(main):001:0> {|x| x*x}
SyntaxError: compile error

we’ll get a compile error. But blocks can be very powerful and go by the hand with other important concept in Ruby, namely the Procs. Procs, put again in a simple way, are blocks given life, thus are blocks bounded to some variables they can work with. To create a new proc, we can simply call the constructor of the class Proc or the kernel reserved word lambda, what will get us to the same thing, except that the latter will provide us argument checking. Thus:

March 13, 2008

class EnumerableAttribute
attr_reader :values
def initialize(*args)
@values = Hash.new
0.upto(args.size-1) do |i|
@values[args[i].to_s] = i
end
@values.each do |key, value|
EnumerableAttribute.class_eval do
define_method key do
value
end
end
end
end
end

This class allows the dynamical creation of enumerable types mapped to integers in the database, starting from 0. The constructor will take a list of symbols representing the keys and will create a Hash that will map each key to one integer value. Once created, we can have access to the Hash via the method values or to the integer value of each key via the method called like the symbol.