dynamically assigning class constants

P

Pete Hodgson

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
 
M

Miles Georgi

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__)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top