From: Raul Jara Date: 2010-02-28T07:32:11+09:00 Subject: Re: scope question Nick Brown wrote: > Consider the following Sinatra app: > > require 'sinatra' > vara = "foo" > VARB = "bar" > helpers do > def geta > vara > end > def getb > VARB > end > end > get '/a' do geta end > get '/b' do getb end > > When I run that and browse to /b, it displays "bar". When I browse to > /a, however, it produces the error: "undefined local variable or method > `vara'". > > Why do these two variables differ in scope? > > How can I declare a variable that has global scope but is not a > constant? > > Thanks in advance... Important disclaimer: I'm kind of new at this, so I'm just taking a stab at it... One way you could do that is to declare a class variable for the class Object. Because every object inherits from Object, everything in ruby should have access to that same class variable. E.g., class Object @@var = "Hello" end puts @@var >Hello class Silly def Silly.hi puts @@var end end Silly.hi >Hello @@var = "goodbye" Silly.hi >goodbye But it's generally considered good form to not use global variables in the first place. There's almost always a way to avoid using them. The danger of using them is that if you use a global variable with your code, and someone else uses a global variable of the same name in their code, the two bits of code will both break if they are ever run together. -- Posted via http://www.ruby-forum.com/.