什么是带上下文的 Ruby 方法定义?
最近我遇到了一些如下所示的 Ruby 代码:
module SomeModule
class SomeClass
def hire_an_employee business
# do stuff
end
end
end
我以前从未见过 def 语法。
在 Pickaxe 书中,方法定义如下:
def defname⟨(⟨,arg⟨,=val⟩⟩∗ ⟨,&blockarg⟩) ⟩
body
end
它指出“defname 既是方法的名称,也可以是方法有效的上下文”。但它似乎没有提供任何进一步的解释。
我的问题是:有人可以通过上下文更好地解释此方法定义,并举例说明如何使用它吗?
Recently I've run across some Ruby code that looks like this:
module SomeModule
class SomeClass
def hire_an_employee business
# do stuff
end
end
end
I have never seen that def syntax before.
In the Pickaxe book, method definition is as follows:
def defname⟨(⟨,arg⟨,=val⟩⟩∗ ⟨,&blockarg⟩) ⟩
body
end
and it states that "defname is both the name of the method and optionally the context in which it is valid." However it doesn't seem to offer any further explanation.
My question is: Can someone give a better explanation for this method definition with context and give an example of how it might be used?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该代码示例在 模块 中定义了一个类。该类有一个名为
hire_an_employee
的方法,采用单个参数business
。方法定义本身没有什么异常,除非您指的是缺少的括号。定义方法时(以及调用方法,除非需要消除歧义),括号是可选的。
“上下文”部分意味着
defname
可以包含上下文(如self
)来定义类(而不是实例)方法。The code sample defines a class within a module. The class has a single method named
hire_an_employee
, taking a single parameterbusiness
. There's nothing unusual about the method definition itself, unless you're referring to the missing parentheses.Parens are optional when defining a method (and calling one, unless needed for disambiguation).
The "context" part means that
defname
can include a context, likeself
, to define a class (as opposed to instance) method.给定:
使用函数 'hire_an_employee'
Ps:您可以省略括号。
与以下相同:
Given:
To use the function 'hire_an_employee'
Ps: You can omit the parens.
is the same as: