1

@ - instance variable @@ - class variable.

So instance variable value shouldn't be shared if no instance is created. But:

class Add

  def self.add(what)
    if not defined? @a
      @a = 0
    end
    @a += what
    puts @a.to_s
  end
end

Add.add(4)
Add.add(4)

Results in:

$ruby main.rb

4
8

Why?

1
  • 2
    Aside: @a ||= 0 is a commonly-used replacement for if not defined? @a.... The former is shorthand for @a = @a || 0, just as x += 1 is for x = x + 1. Commented Nov 13, 2013 at 16:48

2 Answers 2

3

Every class in Ruby is also an object, instance of Class class. So, your @a is simply instance variable of Add class.

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

6 Comments

Ok then why Add.add(4) run for the second time results in 8. @a is not global
@user665967 it's because @a is instance variable of Add class. When you modify instance variable value of some object, and that object persist, its instance variable persists as well.
Correct me if I'm wrong, so basically @variables in Class methods are instance variables but automatically become Class variables on the Object level
@user665967 no. The point is that in Ruby every class is also an object with all consequences. One of these consequences is the fact that it has its own instance variables. So if you define "class method" and you use instance variable inside of it, this instance variable belongs to this class instance. And, what's important, it's NOT a class variable, which is a bit different concept.
Marek, how can I contact you? :)
|
2

The @a you are referring to in the singleton method is an instance variable of Add's class.

You have effectively changed the scope of the method declaration to the eigenclass when you have defined the method as def self.add instead of def add.

4 Comments

Why 'eigenclass'? It's an instance variable of object itself (which is Add class), not its eigenclass: (class << Add; self end).instance_variable_get(:@a) # => nil
@MarekLipka please, read up the section about class methods in the second link and you might reconsider the downvote. tl;dr: all class methods are housed in the eigenclass of the particular Class instance.
it's not about "class method" (which is, of course, right that they are housed in eigenclassess of the particular Class instance). It's about instance variables. Please take my example into consideration.
@MarekLipka - I see, you're right. Leave the downvote, it is deserved. Thank you for this small instant of enlightenment :) I will remove the eigenclass.

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.