Okiba Okiba - 2 years ago 72
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?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download