meizin
meizin

Reputation: 221

Variable behavior in Ruby

I have this weird case I can not explain:

@@test = 1234

def m
  puts @@test
end

class Test
  @@test = 5678
end

m

if I do not define 5678, then output is 1234.

if I do not define 1234, then undeclared variable error.

Now, if I define 1234, the output is 5678, why?

I am really confused by this.

Upvotes: 1

Views: 48

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118299

If I do not define 5678, then output is 1234.

This is because @@test is a class variable, which is shared between its class's children classes. You defined it on the top level, and the toplevel has the scope of the class Object, and method m becomes the private method of the Object class. So while you are calling m from the top level, you are getting the output as 1234.

Now, if I define 1234, the output is 5678,

As I said class variables are shared. Test by default is the child class of Object. And inside the Test you had modified the shared variable @@test. That's why now calling m is giving the current updated value of @@test which is 5678.

if I do not define 1234, then undeclared variable error.

Nothing wrong. If you try to use the class variable before defining them, you will get the exception as uninitialized class variable @@test.

Upvotes: 3

Related Questions