模块结构,Ruby中的模块A模块B模块C是什么意思?

发布于 2025-02-04 22:04:42 字数 337 浏览 1 评论 0原文

我是Ruby的新手,并查看了源代码。我看到它在查找什么是一个模块的顶部说

module a module b module c
 module d

  def foobar

,它类似于类。我已经看到了

module a
 module b
  def foobar 

在模块中定义一个模块的示例,我理解了这个概念,但我没有获得模块链。

另外,我认为

module a; module b;
module c
 def foorbar

为什么现在有分号?

I am new to Ruby and looking at a source code. I see it says on top

module a module b module c
 module d

  def foobar

From looking up what a module is, it is similar to class. I have seen examples of

module a
 module b
  def foobar 

where a module is defined in module, which i understand this concept but i do not get the chain of modules.

Also, i have seen it as

module a; module b;
module c
 def foorbar

why is there semicolon now?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

蓝天白云 2025-02-11 22:04:42

这不是有效的Ruby:

module a module b module c

这是潜在的有效命名区域,尽管在Ruby中,所有模块和类名称(但不是方法)必须是常数。在这种情况下,这意味着他们需要从大写字母开始。这些模块还需要用最终语句关闭:

module A
  module B
    def foobar
    end
  end
end

半洛龙表示陈述之间的断裂。有时,人们会用它们来使事情变得短,或者将剪切和剪切成诸如IRB之类的卧式,但这不是很好的编码练习。例如,这是一条有效的单线,其执行与上述相同:

module A; module B; def foobar; end; end; end

如果您在IRB上使用3.1.2(3.1.2)的最新版本,您甚至会得到有用的例外,告诉您代码有什么问题:

 类/模块名称必须是恒定的(SyntaxError)  
模块A。  
       ^
 

我建议阅读 Ruby Syntax像irb(标准标准配置的)或 tryruby 在线。

This is not valid Ruby:

module a module b module c

This is potentially valid namespacing, although in Ruby all module and class names (but not methods) must be constants. In this case, that means they need to start with capital letters. The modules also need to be closed with end statements:

module A
  module B
    def foobar
    end
  end
end

Semicolons denote a break between statements. Sometimes people will use them to keep things shorter or for cut-and-paste into a REPL like IRB, but it's not good coding practice. For example, this is a valid one-line that does the same as above:

module A; module B; def foobar; end; end; end

If you work in IRB on a recent version of Ruby like 3.1.2, you'll even get useful exceptions that tell you what's wrong with your code:

class/module name must be CONSTANT (SyntaxError)  
module a  
       ^

I suggest reading up on Ruby syntax and testing out code in a REPL like IRB (which comes standard with Ruby) or TryRuby online.

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