15

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?

4
  • 3
    are you on rails on plain ruby? Commented May 13, 2014 at 16:57
  • 1
    Plain ruby. I am aware that Ruby on Rails has a method for this stackoverflow.com/questions/3464007/… Commented May 13, 2014 at 17:00
  • Possible duplicates stackoverflow.com/questions/3464007/… Commented Oct 29, 2019 at 14:49
  • 1
    @EdgarOrtega not a duplicate. That question is for RoR. This question is for just Ruby. Commented Oct 29, 2019 at 17:25

2 Answers 2

34

You can try

class Post
end

Object.const_get("Post")

Which returns the Post class

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

constantize is best than others

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.