From: Gavin Sinclair Date: 2003-11-28T10:31:16+09:00 Subject: Re: Controlled block variables From T. Onama: > > Sorry I let this slip by, I wanted to think on it more. And though I > have, I must admit I'm not quite seeing it --quite possibly my small > brain just isn't cutting it :-) But perhaps too, there's a > communication disconnect. So let me lay down the core problem and you > show me how your solution solves it. That should tell us if were on the > same page. > > a = [1,2,3] > class_eval { > def ameth > p a > end > } > > So the problem is, a will be eval'd as nil, since it is outside of def. Actually, this is the problem: NoMethodError: undefined method `class_eval' for main:Object Or did you mean the above code to exist within a class? If so, I have: class X a = [1,2,3] class_eval { def ameth p a end } end X.new.ameth # NameError: undefined local variable or method `a' for # # from (irb):13:in `ameth' So 'a' is not evaluated as nil, it cannot be evaluated. > To overcome I must convert a to a literal and stick it in a string. class Y a = [1,2,3] class_eval %Q{ def ameth p #{a.inspect} end } end Y.new.ameth # => "[1, 2, 3]" > So how does you solution deal with this problem? I hate to ask at this late stage, but what's the problem? If you want to make the value 'a' available to the dynamically created method 'ameth', maybe you could try this class Z @@a = [1,2,3] class_eval { def ameth @@a.length end } end Z.new.ameth # => 3 If you don't know in advance what your variable names are going to be, use a hash. You don't have to resort to global variables; class variables are there to help. And so am I :) Gavin