How do you convert a string to a variable with Ruby?

I want to convert "something_like_this" to something_like_this.

I added a link to my forms, for example, root_path. I don't want "root_path". Would there be something different from using #{root_path}? It would be nice if there were an opposite of to_s.

2 answers

  • answered 2017-11-12 19:52 Martin Zinovsky

    Based on your case I guess you should use Object#send or Object#public_send methods:

    'qwe'.send('upcase') # => "QWE"

  • answered 2017-11-12 20:37 Jörg W Mittag

    You cannot convert a string to a variable, for the simple reason that variables aren't objects in Ruby. If you wanted to convert a string to a variable, you would do that by either calling a method on the string, or by calling a method on some other object as passing the string as an argument. Either way, the variable would have to be returned by the method, but methods can only return objects and variables aren't objects.