But unfortunately I have to call two such functions in chain and both
have a block as parameter, so eval would be my last choice. So I'm
looking for a way to call the function like I could call them if it
would be an Object Method:
Class.get_objet_by_name("ClassName").send(:name)
any suggestions?
best regards
Not sure if I understood correctly, but anyway...
str = String.new("ruby")
obj_name = "str"
eval(obj_name).send("length")
=> 4
Would something like this work?
Premshree
Hi Premshree,
> Not sure if I understood correctly, but anyway...
For sure my fault ;-)
> str = String.new("ruby")
> obj_name = "str"
> eval(obj_name).send("length")
> => 4
>
> Would something like this work?
Jep, that's exactly what I was looking for. I wondered what Type the
expression /eval("str")/ would have and instead of asking here I
thought: "Hey that's ruby why not asking the result itself" =>
So :
puts eval("Test").inspect
Test
So am I'm right that eval("Classname") returns some kind of "default
initialized" Object of type Classname?
best regards and thanks,
Torsten
Object.const_get("ClassName").foo
Cheers,
Daniel
Daniel Schierbeck wrote:
> Object.const_get("ClassName").foo
ri const_get
------------------------------------------------------- Module#const_get
mod.const_get(sym) => obj
------------------------------------------------------------------------
Returns the value of the named constant in _mod_.
Math.const_get(:PI) #=> 3.14159265358979
Is a class name treated like a constant in ruyb? Or is my documentation
not up to date? Or is it just an undocumented feature?
Thanks,
Torsten
Both classes and modules are constants -- this is valid:
Foo = Class.new{}
Bar = Module.new{}
If you want to make sure the object returned by Module#const_get is a
class, you can just test its class:
class Module
def class_get(name)
cl = const_get(name)
unless cl.kind_of? Class
raise TypeError, "`#{cl.inspect}' must be a Class"
end
return cl
end
end
of course, you could also just accept all objects that respond to #new,
which would be quackier:
class Module
def class_get(name)
cl = const_get(name)
unless cl.respond_to? :new
raise TypeError, "`#{cl.inspect}' must respond to `new'"
end
return cl
end
end
Cheers,
Daniel
> Torsten Robitzki wrote:
>
>> Is a class name treated like a constant in ruyb? Or is my
>> documentation not up to date? Or is it just an undocumented feature?
>
>
> Both classes and modules are constants -- this is valid:
>
> Foo = Class.new{}
> Bar = Module.new{}
> ...
Thank you for your detailed and very helpful reply. Tomorrow I will have
to travel by train, so that's a good opportunity to read my "Programming
Ruby" book ;-)
best regards
Torsten
No problem at all :)
Daniel