Ruby 什么是自我。在课堂教学法中是什么意思?
在Ruby编程中,我看到一个类方法被定义为Ruby 什么是自我。在课堂教学法中是什么意思?,ruby,Ruby,在Ruby编程中,我看到一个类方法被定义为 class File def self.my_open(*args) #... end end 前缀“self.”在这里是什么意思 使用语法def receiver.method可以在特定对象上定义方法 现在让我们看一下这两个类: class Foo def self.hello "hello from Foo" end end class Bar end Foo.class # => Class Bar.cla
class File
def self.my_open(*args)
#...
end
end
前缀“self.”在这里是什么意思 使用语法
def receiver.method
可以在特定对象上定义方法
现在让我们看一下这两个类:
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)
塞尔吉奥解释得很好。我想我会补充一点,让noobs(带着最大的敬意)更简单——他们可能很难理解上述答案 (1)什么是方法? 想想一个人。人可以做某些动作。e、 我们可以走路、说话、开车、喝大量的酒等。这些类型的行为被称为“方法” (2)有些方法只能由某些人执行 例如,只有泰格·伍兹能以漂亮的小落差将球打出330码。不是所有的人都能用这种方法……另一个例子是:只有迈克尔·杰克逊能像国王一样唱歌和走路 让我们假设我们创造了一个人。(即,我们正在创建person对象)
Freddie_Mercury=Person.new
Freddie_Mercury.DriveGolfBall#~>-:15:in`':Person:Class(NoMethodError)的未定义方法“DriveGolfBall”
弗雷迪不会开高尔夫球。该方法不是“类方法”
(3)“Self”前缀创建了所有人都可以使用的方法。它创建类方法
如果我想创造一种世界上每个人都能做到的方法:呼吸法。所有人都能呼吸。如果他们不能,他们就会死
(4)如何调用该方法?
如果我想呼吸,我会说“人,呼吸”。我不会说“FreddieMercury.呼吸”。不需要对特定的人调用该方法,但我会对整个物种调用该方法:我会在person类上调用它。在谷歌搜索“Ruby Self”时,从中可以看到:“Ruby中的关键字Self使您可以访问当前对象–接收当前消息的对象。”在
Ruby
中对self
进行了很好的解释。是的。这也是我联系的问题。我不知道问题有多糟。def self.foo
中的self
确实意味着它所处的类别,但是,现在不清楚为什么def foo
并不意味着相同的事情,因为省略作为接收者的self
通常没有效果。我想这才是问题的关键。谢谢,萨瓦。当问题被关闭时,我正在作答。您好,谢谢@SergioTulentsev-基本上self.method_name允许直接对类调用方法,而不必创建类的实例?@BKSpurgeon:类似这样的,是的。
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)
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"
Freddie_Mercury = Person.new
Freddie_Mercury.DriveGolfBall # ~> -:15:in `<main>': undefined method `DriveGolfBall' for Person:Class (NoMethodError)