From: Gregory Brown Date: 2008-10-23T23:00:08+09:00 Subject: Re: Is there a method_eval or similar thing ? On Thu, Oct 23, 2008 at 8:12 AM, Nit Khair wrote: > Brian Candler wrote: >> However you could turn it around and get the caller to pass a >> pre-prepared hash containing all the bindings to askyn: >> >> askyn("Do you wish to proceed?", "n", >> :yes => lambda { puts "user pressed yes" } >> :no => lambda { puts "user pressed no" } >> ) >> > > That is something which immediately struck me as a possibility since I > was considering putting some configurations into a hash anyway. > > askyn("Do you wish to proceed?", config = {}, &block) > > I had thought that would be ugly, and I might be missing something > elegant and simple. However, perhaps that *is* the simple way to go. How about this? (Someone suggested before using an object to abstract your needs, I've only implemented it) class Answer def yes(&block) @yes = block end def no(&block) @no = block end def process(string) (string =~ /\by(es)?\b/i ? @yes : @no).call end end def ask_yn(question, &block) ans = Answer.new ans.instance_eval(&block) ans.process(gets.chomp) end ask_yn("Are you cool?") do yes { puts "Awesome" } no { puts "Lame" } end -- Technical Blaag at: http://blog.majesticseacreature.com | Non-tech stuff at: http://metametta.blogspot.com