I'll try to post a code to explain it. If you don't understand, please ask me in the comments.
#!/usr/bin/env ruby
# encoding: UTF-8
class Trivia
@@x = 10
def instance_scope_x
@x
end
def instance_scope_x=(x)
@x = x
end
def self.class_scope_x
@@x
end
def self.class_scope_x=(x)
@@x = x
end
end
a = Trivia.new
# 只有Trivia对象才能使用class方法。所以这里用a.class返回Trivia对象
p "The class scope x in a : #{a.class.class_scope_x}"
a.instance_scope_x = 20
p "The instance scope x in a : #{a.instance_scope_x}"
b = Trivia.new
# Trivia的实例修改自身的值,不会影响同个类的其他实例
p "The instance scope x in b : #{b.instance_scope_x}"
p "The class scope x in b : #{b.class.class_scope_x}"
b.class.class_scope_x = 30
# 修改了Trivia类的值。因为a和b共享同一个类对象(都指向Trivia),所以现在值改变了
p "Now the class scope x in a : #{a.class.class_scope_x}"
# self指向当前作用域的所有者
class Trivia
# 类作用域
p self
def self_scope_x
# 实例作用域
p self
# 这里self指向实例作用域
self.instance_scope_x
end
def self.self_scope_x
# 这里self指向类作用域
self.class_scope_x
end
end
p "The self_scope_x in Trivia: #{Trivia.self_scope_x}" # 调用的是class_scope_x
p "The self_scope_x in Trivia's instance: #{a.self_scope_x}" # 调用的是instance_scope_x
I'll try to post a code to explain it. If you don't understand, please ask me in the comments.
I will explain these issues in the article, welcome to pay attention