Convert string to class name without using eval in

2019-02-08 21:16发布

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?

2条回答
神经病院院长
2楼-- · 2019-02-08 21:26

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
查看更多
我只想做你的唯一
3楼-- · 2019-02-08 21:47

You can try

class Post
end

Object.const_get("Post")

Which returns the Post class

查看更多
登录 后发表回答