将字符串转换为类名,而不使用ruby中的eval? [英] Convert string to class name without using eval in ruby?
本文介绍了将字符串转换为类名,而不使用ruby中的eval?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的:
string =Post
/ pre>
我想将字符串转换为类名字面值。我使用eval这样来转换字符串:
eval(string)#=> Post
作为一个javaScript开发人员,我试图避免eval。有没有更好的方法这样做在Ruby?
解决方案您可以尝试
class Post
end
Object.const_get(Post)
这会返回
Post
类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?
解决方案You can try
class Post end Object.const_get("Post")
Which returns the
Post
class这篇关于将字符串转换为类名,而不使用ruby中的eval?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文