Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string to a constant in Ruby?

Tags:

ruby

How to convert the string "User" to User?

like image 402
marshluca Avatar asked Mar 02 '10 06:03

marshluca


People also ask

How do you convert a string to a constant in Ruby?

No need to require ActiveSupport. Usage example: class User; def self. lookup; const_get('SomeClassName);end; end User. lookup will return class itself.

How do you create a constant in Ruby?

Ruby ConstantsConstants begin with an uppercase letter. Constants defined within a class or module can be accessed from within that class or module, and those defined outside a class or module can be accessed globally. Constants may not be defined within methods.

What is :: in Ruby?

The :: is a unary operator that allows: constants, instance methods and class methods defined within a class or module, to be accessed from anywhere outside the class or module.


1 Answers

Object.const_get("User") 

No need to require ActiveSupport.

like image 177
Damien Avatar answered Sep 19 '22 12:09

Damien