Robert Klemme
3/29/2009 3:55:00 PM
On 29.03.2009 16:38, Pascal J. Bourguignon wrote:
> Robert Klemme <shortcutter@googlemail.com> writes:
>
>> On 29.03.2009 13:40, Brian Candler wrote:
>>>> frank = Object.const_get("Master::Person").new("Frank")
>>>>
>>>> Does anyone know why the second way fails?
>>> frank = Master.const_get("Person").new("Frank")
>> Erm, that's a hybrid solution. If you know the names beforehand, you
>> can just do
>>
>> frank = Master::Person.new "Frank"
>
> Then the answer for the OP would be:
>
> frank = Object.const_get("Master").const_get("Person").new("Frank")
Why would anyone want to use Strings when he knows the names (and
consequently their number) beforehand? That does not make sense.
> const_get takes only a simple constant name, not a qualified name.
Yes, and that's why the solutions that were provided use some form of
String#split to cut a fully qualified name down to individual constants.
>> I would assume that the OP receives the full qualified name as a
>> String and wants to get the class from there which can only be
>> achieved with any of the other solutions shown.
>
> Obviously, he wants to replace the literals by variables.
Apart from the plurals:
> This works:
>
> john = eval("Master::Person").new("John")
>
> This fails:
>
> frank = Object.const_get("Master::Person").new("Frank")
Regards
robert