From: Joel VanderWerf Date: 2002-12-10T06:26:07+09:00 Subject: Re: Newbie: invoking class methods 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, This is one way of limiting what actions the file can do: module GameModule class Game def self.new super end end end cmd = "Game.new" klass_str, meth = cmd.split(/\./) unless GameModule.constants.include? klass_str raise "Unrecognized class #{klass_str}" end klass = GameModule.const_get(klass_str) unless klass.singleton_methods.include? meth raise "Unrecognized method #{meth} for class #{klass}" end p klass.send(meth)