Ruby: Convert string to class 字符串转换成类的两种方式


I was performing the same operation on multiple classes and wanted to DRY up my code.
我想提升我的代码, 针对不同的class上的相同的操作代码问题.
DRY: 不要重复你自己.

If you have a string with the class name you can retrieve the class object to perform operations with it like so:
如果你有个字符串是class的名字,你可以retrieve检索 class object 类对象去执行操作. 比如:

In Rails 
clazz = 'YourClassName'.constantize

In Ruby without Rails 
clazz = Kernel.const_get('YourClassName')

阅读量: 712
发布于:
修改于: