From: J2M Date: 2006-12-12T23:59:28+09:00 Subject: Re: How do I catch a missing method on a passed block? dblack@wobblini.net wrote: > Hi -- > > > class Foo > > def bar(quantal, *args, &block) > > if block_given? > > lambd = lambda(&block) > > class << lambd > > @@return = {}.extend(Appenders::Hashs) > > def method_missing(m, *args, &block) > > return @@return << { m.to_sym => args_to_attributes(args) } > > I'm curious where args_to_attributes is defined. Is it a top-level > method? I just include it into the singleton class, I just chopped it out here! > > > end > > end > > attributes = lambd.instance_eval(&lambd) > > end > > parse quantal, attributes > > If that if block hasn't run, attributes is going to be undefined. Did > you mean to put this line inside the block? If no block is passed, I had some code (that is snipped for the sake of brevity) to build the attributes. Sorry lazy cut and paste job, I should have stripped it back to the original question. > > > end > > end # Foo > > > > What made this sweet for me was turning the &block into a lambda let me > > return the result from the instance_eval to bar where other solutions > > kept them in scope of the &block. > > But the block *is* a lambda :-) That's what the &block argument does: > it captures the code block in an object and assigns a variable to it. But without the lambda it is a raw proc that doesn't return the result of the method - from what I understand from page 344 of Pickaxe. I tried without and didn't get the result passed back from method_missing, but I will now test that again :-) > You could probably also get rid of the class variable by using > define_method. (Not essential, but always a bit of a plus style-wise, > I think.) Sweet, didn't think of that, I was wanting to get rid of it. Thanks David.