Dynamically assigning class constants

Hi folks,

I have a class definition as follows:

class Level
attr_reader :name, :rank
def initialize( name, rank )
@name, @rank = name, rank
end

TRACE = Comparable.new( :TRACE, 1000 )
DEBUG = Comparable.new( :DEBUG, 2000 )
INFO = Comparable.new( :INFO, 3000 )
# etc

end

and I’d like to define the constants in a more ruby-esque way; something
like:

class Level
attr_reader :name, :rank
def initialize( name, rank )
@name, @rank = name, rank
end

%w{TRACE DEBUG INFO CHANGE WARN ERROR FATAL}.each_with_index do 

|name,i|
clever_dynamic_hackery( name, Comparable.new( name.to_sym, i*1000
) )
end

end

but I don’t know what that clever_dyanamic_hackery method should
actually be. Any one want to show me the light?

Cheers,
Pete

Apologies, s/Comparable/Level/ in the example code.

module M
%w(FOO BAR BAZ).each do |c|
const_set(c, 1)
end
end

there might be a method for specifically creating constants,but if not
you could always do something like this:

module_eval("#{name} = #{i*1000}", FILE, LINE)

Wonderful, thank you Xavier!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs