什么是带上下文的 Ruby 方法定义?

发布于 2024-12-14 10:54:23 字数 405 浏览 0 评论 0原文

最近我遇到了一些如下所示的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你的背包 2024-12-21 10:54:23

该代码示例在 模块 中定义了一个类。该类有一个名为 hire_an_employee 的方法,采用单个参数 business。方法定义本身没有什么异常,除非您指的是缺少的括号。

定义方法时(以及调用方法,除非需要消除歧义),括号是可选的。

“上下文”部分意味着 defname 可以包含上下文(如 self)来定义类(而不是实例)方法。

class Foo
  def self.ohai
    p "kthxbai"
  end
end

> Foo.ohai
kthxbai
> Foo.new.ohai
NoMethodError: undefined method 'ohai' ...

The code sample defines a class within a module. The class has a single method named hire_an_employee, taking a single parameter business. 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, like self, to define a class (as opposed to instance) method.

class Foo
  def self.ohai
    p "kthxbai"
  end
end

> Foo.ohai
kthxbai
> Foo.new.ohai
NoMethodError: undefined method 'ohai' ...
你与昨日 2024-12-21 10:54:23

给定:

module SomeModule
  class SomeClass
    def hire_an_employee business
      # do stuff
  end
end

使用函数 'hire_an_employee'

k = SomeModule::SomeClass.new
k.hire_an_employee "woot"

Ps:您可以省略括号。

def foo(a)
  #do stuff
end

与以下相同:

def foo a
  #do stuff
end

Given:

module SomeModule
  class SomeClass
    def hire_an_employee business
      # do stuff
  end
end

To use the function 'hire_an_employee'

k = SomeModule::SomeClass.new
k.hire_an_employee "woot"

Ps: You can omit the parens.

def foo(a)
  #do stuff
end

is the same as:

def foo a
  #do stuff
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文