From: Tim Hunter Date: 2002-12-10T08:23:31+09:00 Subject: Re: Newbie: invoking class methods On Mon, 09 Dec 2002 20:55:42 GMT, jd204c@nih.gov (James Davis) wrote: >(Using Ruby 1.6.6) >I am writing a game. A "splash" screen displays four buttons to the >user. Each button has an action assigned to it, loaded from a file. >When a user clicks a button, I want to execute a class method such as >Game.new. First, I thought I wanted a Proc for this purpose, so I >tried: > ba = proc {ba} # ba = "Game.new" >... > ba.call >This approach didn't work. Didn't produce errors. So I switched to > eval(ba) >which does work, but I was hoping for a better technique. Eval seems >crude and unsafe to me, particularly since the button actions are >loaded from a file. I am wondering if there might be another approach >such as something like "instance_method" for class methods, or send, >or yield. Any advice appreciated. Thanks, > >- Jim Davis - It's not clear to me what the "action" can be, however, I'll offer the following thoughts. If the "action" is always a the name of a Game class method, convert the name to a symbol and send it to the Game class: m = "new" Game.send m.intern If the "action" is always the name of a class and the name of a class method in the class (i.e. "Game" and "new") then you can get the class id from the class name with Class.get_const. c = Class.get_const "Game" m = "new" c.send m.intern