11

What does it mean to create an instance variable, say @foo in a file outside any class definition. Say there is a file, test.rb and the entire contents of the file are given below.

# test.rb
@foo = "bar"
puts @foo

It prints "bar", but is this an instance variable in some sort of wrapping class?

Testing using two files indicates that there is a main object that everything is wrapped inside. Is this understanding correct?

Contents of a.rb

@me = self
@a = "from-a"

Contents of b.rb

require "./a"

@b = "from-b"
puts @me == self # true (self refers to the same object)
puts self.class  # Object
puts self.instance_variables # [@a, @b, @me]

1 Answer 1

18

Everything is an object in ruby. So you are actually in the main object right now, which is an instance of Object.

In your file, if you put puts self.class, you will see you are operating under main, and the class being Object.

Even in irb, for example:

ruby-1.9.2-p136 :001 > self
 => main 
ruby-1.9.2-p136 :002 > self.class
 => Object 
Sign up to request clarification or add additional context in comments.

2 Comments

Is main an instance of Object that everything operates under?
how is the main Object shared in a multi-user web application? e.g. let's say I have a file 'x.rb' I import in a Rails or Sinatra application. If one user requests calls a method in that file that sets @a = 5, and then another user calls a method in that file that retrieves @a, will the second user receive a value of 5? Or Do Rails/Sinatra create a separate instance of the Object class of that file for each separate user request?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.