Convert string to class name without using eval in ruby?

孤人 提交于 2020-01-21 03:02:30

问题


I have something like this:

string = "Post"

I would like to convert the string to a class name literal. I use eval like this to convert the string:

eval(string) #=> Post

Being a javaScript developer I try to avoid eval. Is there a better way of doing this in Ruby? Or is using eval the preferred way of handling this?


回答1:


You can try

class Post
end

Object.const_get("Post")

Which returns the Post class




回答2:


Use Module.const_get

string = "Fixnum"
clazz = Object.const_get(string)
clazz.name # => "Fixnum"

If you are in a rails context, you can also use the `#constantize method on string

clazz = string.constantize # => Fixnum


来源:https://stackoverflow.com/questions/23637313/convert-string-to-class-name-without-using-eval-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!