在Ruby中反映。用给定的类名实例化一个对象。

时间:2021-03-07 16:24:12

I came to ruby from PHP. How could i do the next thing in ruby?

我是从PHP开发ruby的。我怎么能用ruby做下一件事呢?

$className = 'ArrayObject';
$arrayObject = new $className();

3 个解决方案

#1


27  

You can do this:

你可以这样做:

arrayObject = Object::const_get('Array').new

#2


16  

You can also use the following if you are using Ruby on Rails:

如果您正在使用Ruby on Rails,也可以使用以下内容:

array_object = "Array".constantize.new

#3


4  

If you have a class, like for example String:

如果你有一个类,例如字符串:

a = String
a.new("Geo")

would give you a string. The same thing applies to other classes ( number & type of parameters will differ of course ).

会给你一根绳子。同样的事情也适用于其他类(参数的数量和类型当然会有所不同)。

#1


27  

You can do this:

你可以这样做:

arrayObject = Object::const_get('Array').new

#2


16  

You can also use the following if you are using Ruby on Rails:

如果您正在使用Ruby on Rails,也可以使用以下内容:

array_object = "Array".constantize.new

#3


4  

If you have a class, like for example String:

如果你有一个类,例如字符串:

a = String
a.new("Geo")

would give you a string. The same thing applies to other classes ( number & type of parameters will differ of course ).

会给你一根绳子。同样的事情也适用于其他类(参数的数量和类型当然会有所不同)。