From: Glen Holcomb Date: 2008-08-29T05:07:15+09:00 Subject: Re: Use a string as a method call ------=_Part_8979_6528854.1219954320776 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline On Thu, Aug 28, 2008 at 2:02 PM, Chris Bailey < christopher.sean.bailey@gmail.com> wrote: > I'm trying to come up with an efficient way of using user input as a > way of calling methods. I'm unhappy with the way that I am doing it > because it isn't very flexible. This is what I'm doing now. > > input = gets.downcase.chomp > > if input == foo > do_foo() > elsif input == bar > do_bar() > else > puts "That isn't a command!" > end > > What I would like to do is more like so. > > commands = { > 'foo' => do_foo(), > 'bar' => do_bar() > } > > I then would like to search the commands hash for a key that matches the > player input and execute the method associated with that key. What I've > noticed is that upon initialization of the hash the value becomes equal > to the result of the method but that is not what I want. If I store the > value as a string ie "do_foo()" would I be able to parse that string and > execute it as a method? And if so, how would that be done? > -- > Posted via http://www.ruby-forum.com/. > > You could do it with eval in this case it sounds like that would be fairly safe although you could also use a proc I think. -- "Hey brother Christian with your high and mighty errand, Your actions speak so loud, I can't hear a word you're saying." -Greg Graffin (Bad Religion) ------=_Part_8979_6528854.1219954320776--