From: Mike Gold Date: 2008-11-01T05:19:31+09:00 Subject: Re: How to access to local variables in enclosing scopes? Yuh-Ruey Chen wrote: > This is not what I'm really looking for. I don't care about accessing > variables within another unrelated scope - in fact, unless explicitly > allowed, it should not be allowed. I only care about accessing > variables in enclosing scopes. Just to verify we are on the same page: define_method solves all your problems, right? If you don't wish to use Ruby 1.9 (which will be officially released in two months) then the corner case is default arguments, which can be done via the example I gave. Keep in mind that you are looking at just one side of the coin. There's a flip side to it. Preventing local variables from willy-nilly infecting your methods is a Good Thing, and is usually what you want. > x = 10 > > def foo > # how to access x from here? > end > > class Klass > # how to access x from here? > def bar > # how to access x from here? > end > end If you really want x to be globally accessible then you should do require 'ostruct' GLOBALS = OpenStruct.new GLOBALS.x = 10 def foo GLOBALS.x end class Klass GLOBALS.x def bar GLOBALS.x end end This makes your intention explicit. If you know python, you've probably heard the phrase, "Explicit is better than implicit." :) -- Posted via http://www.ruby-forum.com/.