19

Ruby 中是否有引用类的当前实例的方法,以self引用类本身的方式?

4

5 回答 5

47

self总是引用一个实例,但一个类本身就是一个Class. 在某些上下文中self会提到这样一个实例。

class Hello
  # We are inside the body of the class, so `self`
  # refers to the current instance of `Class`
  p self

  def foo
    # We are inside an instance method, so `self`
    # refers to the current instance of `Hello`
    return self
  end

  # This defines a class method, since `self` refers to `Hello`
  def self.bar
    return self
  end
end

h = Hello.new
p h.foo
p Hello.bar

输出:

Hello
#<Hello:0x7ffa68338190>
Hello
于 2012-08-22T17:07:13.450 回答
5

在类的实例方法中self引用该实例。要在实例中获取类,您可以调用self.class. 如果你self在一个类方法中调用,你会得到这个类。在类方法中,您无法访问该类的任何实例。

于 2012-08-22T17:08:07.230 回答
3

引用始终可用,它指向的self对象取决于上下文。

class Example

  self  # refers to the Example class object

  def instance_method
    self  # refers to the receiver of the :instance_method message
  end

end
于 2012-08-22T17:13:45.730 回答
3

该方法self引用它所属的对象。类定义也是对象。

如果你self在类定义中使用它是指类定义的对象(到类),如果你在类方法中调用它,它又是指类。

但是在实例方法中,它指的是作为类实例的对象。

1.9.3p194 :145 >     class A
1.9.3p194 :146?>         puts "%s %s %s"%[self.__id__, self, self.class] #1
1.9.3p194 :147?>         def my_instance_method
1.9.3p194 :148?>             puts "%s %s %s"%[self.__id__, self, self.class] #2
1.9.3p194 :149?>             end
1.9.3p194 :150?>         def self.my_class_method
1.9.3p194 :151?>             puts "%s %s %s"%[self.__id__, self, self.class] #3
1.9.3p194 :152?>         end
1.9.3p194 :153?>      end
85789490 A Class
 => nil 
1.9.3p194 :154 > A.my_class_method #4
85789490 A Class
 => nil 
1.9.3p194 :155 > a=A.new 
 => #<A:0xacb348c> 
1.9.3p194 :156 > a.my_instance_method #5
90544710 #<A:0xacb348c> A
 => nil 
1.9.3p194 :157 > 

您会看到 puts #1 在类声明期间执行。它表明这class A是一个 id ==85789490 的 Class 类型的对象。所以内部类声明 self 指的是类。

然后,当在类方法(#2)内部调用self类方法(#4)时,再次引用该类。

当一个实例方法被调用时(#5),它表明它内部(#3)self是指该方法所附加的类实例的对象。

如果您需要在实例方法中引用类,请使用self.class

于 2012-08-22T17:26:54.553 回答
2

可能你需要 :itself 方法?

1.itself   =>  1
'1'.itself => '1'
nil.itself => nil

希望这有帮助!

于 2016-10-28T15:01:12.397 回答