Ruby:类方法与实例方法 AWS 安全 LIVE!

2025-06-08

Ruby:类方法与实例方法

AWS 安全上线!

在 Ruby 中,方法为对象提供功能。类方法为类本身提供功能,而实例方法为类的一个实例提供功能。

考虑以下 Ruby 类:

class SayHello
  def self.from_the_class
    "Hello, from a class method"
  end

  def from_an_instance
    "Hello, from an instance method"
  end
end
Enter fullscreen mode Exit fullscreen mode

这将产生以下结果:

>> SayHello.from_the_class
=> "Hello, from a class method"

>> SayHello.from_an_instance
=> undefined method `from_an_instance' for SayHello:Class


>> hello = SayHello.new
>> hello.from_the_class
=> undefined method `from_the_class' for #<SayHello:0x0000557920dac930>

>> hello.from_an_instance
=> "Hello, from an instance method"
Enter fullscreen mode Exit fullscreen mode

我们不能在类本身上调用实例方法,也不能直接在实例上调用类方法。

Railstips有一篇很好的文章,其中有更多细节,并讨论了创建类方法和实例方法的替代方法。


这有帮助吗?我帮你节省了时间吗?

🫖 给我买杯茶!☕️


另请参阅:Python:类方法、实例方法和静态方法

鏂囩珷鏉ユ簮锛�https://dev.to/adamlombard/ruby-class-methods-vs-instance-methods-4aje
PREV
提高 WebStorm(和其他 JetBrains IDE)的性能
NEXT
Python:什么是*args 和**kwargs?