1

Consider the following code:

@name = 'learning metaprogramming!'

def cap
  @name.upcase # Was expecting to require @@name as the scopes are different like in a class
end

cap # => "LEARNING METAPROGRAMMING!"

Can someone explain, how come I am able to access @name, which I suppose should be the class variable of main.

1 Answer 1

3

@name is an instance variable, @@name would be a class variable.

When you define an instance variable outside any explicit class definition, you implicitly are inside the Object space.

➜  ~  irb
2.1.5 :001 > self.class
 => Object
2.1.5 :002 >

Object is an object, more or less like a custom object. Therefore, when you created

@name = 'learning metaprogramming!'

the instance variable @name exists in the scope of the Object. The method definition happens in the same scope, hence you have accesso the instance variable.

Sign up to request clarification or add additional context in comments.

6 Comments

Then what is the method cap? Is it the instance method or class method of Object?
No, @name, does not exist in the scope of Object, it exists in the scope of main.
@JörgWMittag I know, that's why I used in the scope of the Object instead of in the scope of Object. Feel free to rephrase it if you feel it's confusing. I believe we are meaning the same thing, it is just a possible lack of English communication skills. ;)
@JikkuJose cap is a private instance method of Object.
@MarekLipka okay that sounds meaningful; but I am just finding it confusing as how the inside and outside of a method has the same scope. Won't the act of defining the method change the self into the current scope's instance's scope?
|

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.