Okiba Okiba - 1 year ago 41
Ruby Question

Convert symbol into an object

My method takes an argument. I prefer to avoid directly passing the object like so:

def print_error(Loggers::MyLogger.new, error)

Instead, I would like to pass a symbol like so:

def print_error(:my_logger, error)

Is there an elegant way to convert
symbol into a
instance? Or do I have to build a factory mechanism for that?


In Rails there is a helper ready for that constantize:

#⇒ MyLogger

In Ruby one might do it using Module#const_get:

klazz = :my_logger.to_s.gsub(/(\A|_)(.)/) { |m| m[-1].upcase }
const_get(klazz) if const_defined?(klazz)
#⇒ MyLogger