为什么用self前缀Ruby方法名?

时间:2022-01-26 00:20:25

While looking over some Ruby code I noticed methods declared with self. prepended to the method name. For example:

在查看一些Ruby代码时,我注意到用self声明的方法。以方法名为前缀。例如:

def self.someMethod
  //...
end

What does prepending self. to the method name change about the method?

什么将自我。对方法名更改?

2 个解决方案

#1


10  

def self.something is a class method, called with:

def自我。有些东西是类方法,叫做:

Class.some_method

def something is an instance method, called with:

def something是一个实例方法,用:

class = Class.new
class.some_method

The difference is that one is called on the class itself, the other on an instance of the class.

不同之处在于,一个调用类本身,另一个调用类实例。

To define a class method, you can also use the class name, however that will make things more difficult to refactor in the future as the class name may change.

要定义类方法,您还可以使用类名,但是这将使以后在类名可能更改时重构变得更加困难。

Some sample code:

一些示例代码:

class Foo
  def self.a
    "a class method"
  end

  def b
    "an instance method"
  end

  def Foo.c
    "another class method"
  end
end

Foo.a # "a class method"
Foo.b # NoMethodError
Foo.c # "another class method"
bar = Foo.new 
bar.a # NoMethodError
bar.b # "an instance method"
bar.c # NoMethodError

#2


3  

The self. causes it to become a class method, rather than an instance method. This is similar to static functions in other languages.

自我。使它成为类方法,而不是实例方法。这类似于其他语言中的静态函数。

#1


10  

def self.something is a class method, called with:

def自我。有些东西是类方法,叫做:

Class.some_method

def something is an instance method, called with:

def something是一个实例方法,用:

class = Class.new
class.some_method

The difference is that one is called on the class itself, the other on an instance of the class.

不同之处在于,一个调用类本身,另一个调用类实例。

To define a class method, you can also use the class name, however that will make things more difficult to refactor in the future as the class name may change.

要定义类方法,您还可以使用类名,但是这将使以后在类名可能更改时重构变得更加困难。

Some sample code:

一些示例代码:

class Foo
  def self.a
    "a class method"
  end

  def b
    "an instance method"
  end

  def Foo.c
    "another class method"
  end
end

Foo.a # "a class method"
Foo.b # NoMethodError
Foo.c # "another class method"
bar = Foo.new 
bar.a # NoMethodError
bar.b # "an instance method"
bar.c # NoMethodError

#2


3  

The self. causes it to become a class method, rather than an instance method. This is similar to static functions in other languages.

自我。使它成为类方法,而不是实例方法。这类似于其他语言中的静态函数。