I want to create an object from a class, but the name of that class is
in a variable, so the form obj=Class.new(args) can’t be used. How can it
be done? Without using eval, because its a bit messy and unelegant.
The equivalent of obj=$variable_with_class_name(args) in php.
On Fri, May 05, 2006 at 03:51:39AM +0900, RGR wrote:
} I want to create an object from a class, but the name of that class is
} in a variable, so the form obj=Class.new(args) can’t be used. How can
it
} be done? Without using eval, because its a bit messy and unelegant.
}
} The equivalent of obj=$variable_with_class_name(args) in php.
On Fri, May 05, 2006 at 03:51:39AM +0900, RGR wrote:
} I want to create an object from a class, but the name of that class is
} in a variable, so the form obj=Class.new(args) can’t be used. How can it
} be done? Without using eval, because its a bit messy and unelegant.
}
} The equivalent of obj=$variable_with_class_name(args) in php.
irb(main):002:0> obj = Object::const_get(“Digest::MD5”).new(args)
NameError: wrong constant name Digest::MD5
from (irb):2:in `const_get’
from (irb):2
from :0
I understand the ugliness of eval…but why shouldn’t we use it?
It is
much quicker to write, shorter to read, and easier to use.
Some would say ugly is reason enough. It’s also slower in certain
implementations (YARV). The less eval is used, the less it becomes
the common case and if it’s not the common case it doesn’t have to be
fast.
% cat emergency_inject.rb
module Enumerable
unless instance_methods.include? “inject”
def inject(*seed)
first_item = false
if seed.empty?
first_item = true
else
seed = seed[0]
end
each do |x|
if first_item
seed = x
first_item = false
else
seed = yield(seed, x)
end
end
return seed
end
end
end
We shouldn’t avoid eval just because it takes a second (less on my
computer) to use it 100,000 times. In most situations that is
premature optimisation.
– Elliot T.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.