Arup Rakshit
Arup Rakshit

Reputation: 118271

Confusion with class and instance variable creations

I was playing with the local,class variable and instance variable creation inside the class block as below. But I found something which I failed to explain myself. My confusion has been posted between the two codes below.

class Foo
def self.show
@@X = 10 if true
p "hi",@@X.object_id,x.object_id
end
end
#=> nil
Foo.show
#NameError: undefined local variable or method `x' for Foo:Class
#   from (irb):4:in `show'
#   from (irb):7
#   from C:/Ruby193/bin/irb:12:in `<main>'

The above erros is expected. But in the below code I have assigned the class variable @@X to 10. But in the p statement I used instance variable @X.Why did the error not throw up like the above code ?

class Foo
def self.show
@@X = 10 if true
p "hi",@X.object_id
end
end
#=> nil
Foo.show
"hi"
4
#=> ["hi", 4]

Upvotes: 0

Views: 54

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

Because of everything is object and no explicit variable declaration is required in Ruby, you code

p @X.object_id

silently introduces an instance variable @X (@X.nil? == true). You can see this magic in irb:

~ irb
> p @x.object_id
# 8
# ⇒ 8

Upvotes: 2

Related Questions