From: Sandro Paganotti Date: 2008-10-22T20:42:25+09:00 Subject: Re: Is there a method_eval or similar thing ? ------=_Part_24439_22676840.1224675835269 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline I think that maybe you can wrap everything in a class: class Ask def initialize(question) @question = question; @h={} yield(self) end def actionbind(key, &block) @h[key] = block end end Ask.new("Do you wish to proceed?") do |question| question.actionbind(:yes){ puts "user pressed yes" } question.actionbind(:no) { puts "user pressed no" } end On Wed, Oct 22, 2008 at 9:38 AM, Nit Khair wrote: > I have a method called askyesno which takes a string and returns whether > the user pressed y or n. However, I now want the user to be able to pass > a block in with blocks for what to do for YES and NO. > > However, in this block I need to be able to access method level > variables. Here's how i am trying to code a sample of it. btw, askyesno > will actually sit inside a module in my app. > > -- > # the ch here is only for testing, it contains y or n, so we can test > this out > # easily > > def askyn(str, ch, &bl) > puts str > h = {} > > def actionbind(key, &block) > h[key] = block > end > > if block_given? > method_eval(&bl) # or module_eval etc > end > > case ch > when 'y' > h[:yes].call if h.include? :yes > when 'n' > h[:no].call if h.include? :no > end > end > > askyn("Do you wish to proceed?", 'n') do > actionbind(:yes) { puts "user pressed yes" } > actionbind(:no) { puts "user pressed no" } > end > > > Currently, i have "ask" methods that allow for many options (not just > yes/no), the selection is passed back to the caller and he has a > case-when in which he takes appropriate action. > > I was considering trying out something like the above where he could > pass in proc - bindings for each key. Is there any way to access the > hash "h" from the block ? > -- > Posted via http://www.ruby-forum.com/. > > -- Go outside! The graphics are amazing! ------=_Part_24439_22676840.1224675835269--