B
B
Bohdan_bit2014-06-17 22:03:56
ruby
Bohdan_bit, 2014-06-17 22:03:56

Why is the ruby ​​interpreter behaving so inappropriately?

I'm new to Ruby and during one of my test cases I needed to extend class Module like this:

class Module
  def method
    self.class_eval{@@var = 1}
    self.class_eval{p @@var}
    p self.class_variable_get(:@@var)#1
    p self.class.class_variable_get(:@@var)#2
  end
end

NewClass = Class.new do
end

NewClass.method

ErrorName will appear on line #1
but #2 works fine (but we add a class variable to the newly created class, that is, self, not its class)
Having considered one more example, I generally stopped understanding something
class Module
  def set_class_var(value)
    self.class_eval{@@var = value}
  end

  def get_class_var()
    self.class_variable_get(:@@var)
  end

  def print_class_var
    self.class_eval{p @@var}
  end
end


c = Class.new
c2 = Class.new


c.set_class_var(10)
c.print_class_var #10

c2.print_class_var#10

Tell me where I'm stupid, because I myself can not understand.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dimitriy, 2014-06-18
@Bohdan_bit

According to the first example. method is defined for descendants (instances) of the Module class , Class is inherited from the Module class, so it also has this method.
self - a pointer to the current object, respectively, the scope of the current object.
Since method is a method of descendants, then the scope of self in will be the scope of descendants.
Now, class variable @@ var is defined in Module, is available in Class by inheritance , and will be available in methods of both the class itself and in methods for descendants, respectively, available in method. (You can set up an exchanger for threads, if you put it in a mutex, or make a counter for the number of descendants, well, that's it, for example).
What happens when calling NewClass.method - self points to NewClass , so self.class_variable_get(:@ @var ) tries to access the class variable defined in NewClass but since it is not there, we get error number 1.
p self.class.class_variable_get (:@@ var ) - self.classsets the scope of the Class ( self points to NewClass ) - no error occurs, the class variable is defined.
According to the second example, as I said earlier, a class variable is available both for class methods and for child methods defined in the class, and is one and the same variable, so when it changes in one place, it changes in another.
I explained it as best I could, in general :)
You can read more in detail, for example, here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question