ruby - self. 是什么意思?意思是在类方法中?

标签 ruby

在Programming Ruby中,我看到一个类方法被定义为

class File
  def self.my_open(*args)
  #...
  end
end

前缀“self.”是什么意思?是指这里?

最佳答案

使用语法 def receiver.method 您可以在特定对象 上定义方法。

class Dog
  def bark
    puts 'woof'
  end
end

normal_dog = Dog.new
angry_dog = Dog.new


def angry_dog.bite
  puts "yum"
end


normal_dog.class # => Dog
angry_dog.class # => Dog

angry_dog.bite # >> yum
normal_dog.bite # ~> -:15:in `<main>': undefined method `bite' for #<Dog:0x007f9a93064cf0> (NoMethodError)

请注意,尽管狗属于同一类 Dog,但其中一只狗具有另一只狗没有的独特方法。

类也是一样。在类定义内部,self 指向该类。这对于理解至关重要。

class Foo
  self # => Foo
end

现在让我们看看这两个类:

class Foo
  def self.hello
    "hello from Foo"
  end
end

class Bar
end

Foo.class # => Class
Bar.class # => Class


Foo.hello # => "hello from Foo"
Bar.hello # ~> -:15:in `<main>': undefined method `hello' for Bar:Class (NoMethodError)

即使 FooBar 都是 Class 类的实例(对象),其中之一有另一种方法没有。同样的事情。

如果您在方法定义中省略了 self,那么它就变成了实例方法,它将在类的实例 上可用,而不是在类里面。请参阅第一段中的 Dog#bark 定义。

对于关闭,这里有几个关于如何定义类实例方法的方法:

class Foo
  def self.hello1
    "hello1"
  end

  def Foo.hello2
    "hello2"
  end
end

def Foo.hello3
  "hello3"
end


Foo.hello1 # => "hello1"
Foo.hello2 # => "hello2"
Foo.hello3 # => "hello3"

关于ruby - self. 是什么意思?意思是在类方法中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15539703/

相关文章:

ruby-on-rails - 无法在 Mac OS X 10.8 上使用 Homebrew FreeTds 捆绑安装 tiny_tds

ruby - 如何使用 Ruby 将 STDOUT 复制到文件而不停止它在屏幕上显示

ruby-on-rails - rails 使用用户输入运行 shell 命令

ruby-on-rails - 在 Ruby 中使用 Map 和 Select 方法一起遍历数组

ruby-on-rails - Rails参数,为什么params[ :key] syntax?

javascript - 预加载器不会忽略 websocket - pace js

ruby-on-rails - 如何使用 Ruby 和/或 Rails 检查数组索引是否存在

ruby-on-rails - 如何定义返回带字符串键的哈希的 Factory Girl 工厂?

ruby-on-rails - 用于对象路由的 rails sha1 哈希?

Ruby:#map 对于 bang 方法通常没有意义,是吗?