Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to class name without using eval in ruby?

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?

like image 231
Stratus3D Avatar asked May 13 '14 16:05

Stratus3D


1 Answers

You can try

class Post
end

Object.const_get("Post")

Which returns the Post class

like image 87
MxLDevs Avatar answered Sep 28 '22 15:09

MxLDevs