Wednesday, June 13, 2007

Creating an object from the class name

How do you create an object in Ruby given its class name as a symbol or string?

It turns out that that's not as obvious as using send to call methods in an already existing object. You need to use the Kernel.const_get method to convert your symbol or string into a class reference (in Ruby class names are constants):

def create_object(klass)
  Kernel.const_get(klass).new
end

my_hash = create_object(:Hash)

There's no good reason to use that trick in such a simplistic example, but it could be really helpful if you were reading the class names from a file or when out of the class' scope (perhaps violating encapsulation!).

3 comments:

Ahsan Ali said...

It is useful if you want to create a helper for your views in rails.

<%=create_filter_for :myclassname%>

your create_filter_for method would be:

def create_filter_for(clsname)
raw = Object.const_get(clsname.to_s.camelize)
# and so on.
end

Jeff said...

Rails provides other helper methods in ActiveSupport::CoreExtensions::String::Inflections that are useful here.

Instead of:
raw = Object.const_get(clsname.to_s.camelize)

You can say:
raw = clsname.to_s.classify.constantize

Science said...

You can also do this with eval, which is kind of tacky but effective at times:

str = "Hash"
klass = Kernel::eval(str)
h = klass.new
puts h.inspect
# prints "{}"