Forum: Ruby accessing Class from class symbol

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
treefrog (Guest)
on 2006-02-12 13:08
(Received via mailing list)
Hi,
I'm trying to work out how to access Class methods when I only have the
class symbol

class Foo
   def Foo.hello
      puts "Hello Foo"
   end
end

class Bar
   def Bar.hello
      puts "Hello Bar"
   end
end

str="Foo"

# I could do this, but there must be a better way.
eval "#{str}.hello"

Kernel doesn't have send, so I can't pass the class as a symbol to
Kernel, and then send the method.

Any ideas?

Cheers

Steve
George O. (Guest)
on 2006-02-12 14:18
(Received via mailing list)
"treefrog" <removed_email_address@domain.invalid> writes:

> class Bar
> Kernel doesn't have send, so I can't pass the class as a symbol to
> Kernel, and then send the method.

Kernel does have `send', but classes aren't methods... :-)

Foo and Bar in your case are constants.  Since they're defined at
toplevel scope (i.e., not nested in any class or module definitions),
they're under Object.  So to get the class, do:

  klass = Object.const_get('Foo')  # symbols also accepted

And to call a method, do:

  klass.send('hello')  # symbols also accepted

Hope this helps!
This topic is locked and can not be replied to.