From: Brian Candler Date: 2010-03-01T03:47:40+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? Which two variables? vara is a local variable. Its scope extends to the end of the block where it's defined. However a method definition using 'def ... end' or a class definition using 'class ... end' block starts a fresh empty scope inside it. VARB is not a variable at all, it's a constant. (Constants start with capital letters in Ruby). > How can I declare a variable that has global scope but is not a > constant? $varc is a true global variable. But usually you don't want these. Better is an instance variable of a class (remembering that a class is just an object) class Foo @vard = "hello" def self.vard @vard end def self.vard=(v) @vard=v end end puts Foo.vard Foo.vard = "world" puts Foo.vard Inside an instance method of foo you can use either 'Foo.vard' or 'self.class.vard' to get at this value. -- Posted via http://www.ruby-forum.com/.