module Kernel
def enum(*syms)
new_class = Class.new do
def initialize(name)
@name = name
end
def to_s
"#{self.class.name}::#{@name}"
end
end
syms.each { |type| new_class.const_set(type, new_class.new(type)) }
new_class
end
def enum2(*syms)
syms.each do |sym|
e = Object.new
e.instance_eval("
def to_s
\"#{self}::#{sym.to_s}\"
end
")
const_set(sym.to_s, e)
end
end
end
Above is two types of type safe(I believe :-) Enum.
First type is constant defining style. For example
InstrumentType = enum :GUITAR, :BANJO, :DOBRO
Second type is including style. For example,
module InstrumentType
enum2 :GUITAR, :BANJO, :DOBRO
end
What do you think about above code? Which one is better?
def enum(*syms)
new_class = Class.new do
def initialize(name)
@name = name
end
def to_s
"#{self.class.name}::#{@name}"
end
end
syms.each { |type| new_class.const_set(type, new_class.new(type)) }
new_class
end
def enum2(*syms)
syms.each do |sym|
e = Object.new
e.instance_eval("
def to_s
\"#{self}::#{sym.to_s}\"
end
")
const_set(sym.to_s, e)
end
end
end
Above is two types of type safe(I believe :-) Enum.
First type is constant defining style. For example
InstrumentType = enum :GUITAR, :BANJO, :DOBRO
Second type is including style. For example,
module InstrumentType
enum2 :GUITAR, :BANJO, :DOBRO
end
What do you think about above code? Which one is better?



덧글