[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

accessing Class from class symbol

treefrog

2/12/2006 11:04:00 AM

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

1 Answer

George Ogata

2/12/2006 12:08:00 PM

0

"treefrog" <stephen.hill@motorola.com> writes:

> 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.

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!