Reputation: 48460
I'm not entirely sure how to Google this question, so I come here with an example. I'm looking at a selenium script that has an excerpt like the following:
def setup
@starting_url = "https://www.example.com"
@restricted_url = "https://www.example.com/restricted"
@user_email = "[email protected]"
@user_password = "notarealpassword"
@headless_mode = false
@page_timeout = 15 # seconds
@log_file = 'log/development.log'
@lineup_file = 'data/lineup1.csv'
... more code
end
My question is, why does every variable here get prefixed with an @
symbol? This method is not part of a class. It is being written in the global scope. I understand the variables have significance in with an @
symbol in the case of an explicit class, but what about here?
Upvotes: 2
Views: 201
Reputation: 13665
Those variables become instance variables in the scope of the main
object. They will be available inside other methods also defined at the global scope. Local variables defined within methods at the global scope would go out of scope as soon as the method returned.
Illustration:
def foo
lvar = 1
@ivar = 2
end
def bar
puts @ivar # will print 2 after foo() is called
puts lvar # will throw NameError
end
@ivar # => nil
foo # initializes @ivar
@ivar # => 2
bar # prints 2, throws NameError
lvar # throws NameError
Upvotes: 4