自我是什么在类方法中意味着什么?

时间:2013-03-21 04:46:30

标签: ruby

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

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

前缀“self”是什么。这意味着什么

2 个答案:

答案 0 :(得分:3)

使用语法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"

答案 1 :(得分:0)

Sergio does a fantastic job of explaining it. I thought I would add to it by making it more simple for noobs (with the utmost respect) - who may struggle to understand the above answer.

(1) What is a method?

Think of a human. A human can do certain actions. e.g. we can walk, talk, drive, drink copious amounts of alcohol etc. These types of actions are called: "methods".

(2) There are some methods which can be performed only by some people

For example, only Tiger Woods can drive a ball 330 yards with a beautiful tiny fade. Not all human beings can perform this method......Another example: only Michael Jackson can sing and moon walk like a King.

Let us suppose we create a person. (i.e. we are creating a person object).

Freddie_Mercury = Person.new

Freddie_Mercury.DriveGolfBall # ~> -:15:in `<main>': undefined method `DriveGolfBall' for Person:Class (NoMethodError)

Freddie can't drive golf balls. That method is not a "class method"

(3) The "Self" prefix creates methods which all people can do. It creates class methods

If I want to create a method which every single human being in the world can do: it would be the: breath method. All people can breathe. If they couldn't, they would die.

(4) How would I call the method?

If I wanted some breathing to be done, I would say "Person.breathe". I would not say "FreddieMercury.breathe". There would be no need to call the method on a particular person, but I would call the method on the entire species: I would call it on the Person class.