Ruby 中是否有像 C 中那样的“main”方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9687106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:53:29  来源:igfitidea点击:

Is there a "main" method in Ruby like in C?

rubymain-method

提问by rchn

I'm new to Ruby, so apologies if this sounds really silly.

我是 Ruby 的新手,所以如果这听起来很愚蠢,我深表歉意。

I can't seem to figure out how to write a "main" code and have methods in the same file (similar to C). I end up with a "main" file which loads a seperate file that has all the methods. I appreciate any guidance on this.

我似乎无法弄清楚如何编写“主要”代码并在同一个文件中拥有方法(类似于 C)。我最终得到一个“主”文件,它加载一个包含所有方法的单独文件。我很感激这方面的任何指导。

I spotted the following SO post but I don't understand it: Should I define a main method in my ruby scripts?

我发现了以下 SO 帖子,但我不明白: 我应该在我的 ruby​​ 脚本中定义一个 main 方法吗?

While it's not a big deal, it's just easier being able to see all the relevant code in the same file. Thank you.

虽然这没什么大不了的,但能够在同一文件中查看所有相关代码更容易。谢谢你。

[-EDIT-]

[-编辑-]

Thanks to everyone who responded - turns out you just need to define all the methods above the code. An example is below:

感谢所有回复的人 - 原来您只需要定义代码上方的所有方法。一个例子如下:

def callTest1
    puts "in test 1"
end

def callTest2
    puts "in test 2" 
end

callTest1
callTest2

I think this makes sense as Ruby needs to know all methods beforehand. This is unlike C where there is a header file which clearly list the available functions and therefore, can define them beneath the main() function

我认为这是有道理的,因为 Ruby 需要事先了解所有方法。这与 C 不同,C 有一个头文件清楚地列出了可用函数,因此可以在 main() 函数下定义它们

Again, thanks to everyone who responded.

再次感谢所有回复的人。

回答by dantswain

@Hauleth's answer is correct: there is no mainmethod or structure in Ruby. I just want to provide a slightly different view here along with some explanation.

@Hauleth 的回答是正确的:mainRuby 中没有方法或结构。我只是想在这里提供一个稍微不同的观点以及一些解释。

When you execute ruby somefile.rb, Ruby executes all of the code in somefile.rb. So if you have a very small project and want it to be self-contained in a single file, there's absolutely nothing wrong with doing something like this:

当您执行时ruby somefile.rb,Ruby 会执行somefile.rb. 因此,如果您有一个非常小的项目并希望它独立于单个文件,那么执行以下操作绝对没有错:

# somefile.rb

class MyClass
  def say_hello
    puts "Hello World"
  end
end

def another_hello
  puts "Hello World (from a method)"
end

c = MyClass.new
c.say_hello
another_hello

It's not that the first two blocks aren't executed, it's just that you don't see the effects until you actually use the corresponding class/method.

并不是前两个块没有执行,只是你在实际使用相应的类/方法之前看不到效果。

The if __FILE__ == $0bit is just a way to block off code that you only want to run if this file is being run directly from the command line. __FILE__is the name of the current file, $0is the command that was executed by the shell (though it's smart enough to drop the ruby), so comparing the two tells you precisely that: is this the file that was executed from the command line? This is sometimes done by coders who want to define a class/module in a file and also provide a command-line utility that uses it. IMHO that's not very good project structure, but just like anything there are use cases where doing it makes perfect sense.

if __FILE__ == $0如果直接从命令行运行此文件,该位只是一种阻止您只想运行的代码的方法。 __FILE__是当前文件的名称,$0是 shell 执行的命令(尽管它足够聪明,可以删除ruby),因此比较两者可以准确地告诉您:这是从命令行执行的文件吗?这有时由想要在文件中定义类/模块并提供使用它的命令行实用程序的编码人员完成。恕我直言,这不是很好的项目结构,但就像任何用例一样,这样做很有意义。

If you want to be able to execute your code directly, you can add a shebangline

如果你希望能够直接执行你的代码,你可以添加一个shebang

#!/usr/bin/env ruby

# rest of somefile.rb

and make it executable with chmod +x somefile.rb(optionally rename it without the .rb extension). This doesn't really change your situation. The if __FILE__ == $0still works and still probably isn't necessary.

并使其可执行chmod +x somefile.rb(可选地重命名不带 .rb 扩展名)。这并没有真正改变你的情况。将if __FILE__ == $0仍然有效,仍然可能是没有必要的。

Edit

编辑

As @steenslag correctly points out, the top-level scope in Ruby is an Objectcalled main. It has slightly funky behavior, though:

正如@steenslag 正确指出的那样,Ruby 中的顶级范围是一个Object名为main. 不过,它的行为有点古怪:

irb
>> self
=> main
>> self.class
=> Object
>> main
NameError: undefined local variable or method `main' for main:Object
from (irb):8

Don't worry about this until you start to dig much deeper into the language. If you dowant to learn lots more about this kind of stuff, Metaprogramming Rubyis a great read :)

在您开始更深入地研究该语言之前,请不要担心这一点。如果你确实想了解更多关于这类东西的知识,Metaprogramming Ruby是一个很好的读物:)

回答by Hauleth

No there isn't such structure. Of course you can define main function but it won't be called until you do so. Ruby execute line by line so if you want to print 'Hello World' you simply write:

不,没有这样的结构。当然,您可以定义 main 函数,但在您这样做之前它不会被调用。Ruby 逐行执行,因此如果您想打印“Hello World”,您只需编写:

puts 'Hello World'

The question that you mentioned is about using one file as module and executable, so if you write

你提到的问题是关于使用一个文件作为模块和可执行文件,所以如果你写

if __FILE__ == 
class Foo
  p self
end
#=> Foo

p self
#=> main

def foo 
  p self
end
foo
#=> main
# your code end

It will be called only if you run this file. If you only require it in other file then this code will never run. But IMHO it's bad idea, better option is using RubyGems and there add executables.

仅当您运行此文件时才会调用它。如果您只在其他文件中需要它,那么此代码将永远不会运行。但恕我直言,这是个坏主意,更好的选择是使用 RubyGems 并添加可执行文件。

回答by steenslag

Actually there is a main, but it is not a method; it's the top-level object that is the initial execution context of a Ruby program.

实际上有一个main,但它不是一个方法;它是作为 Ruby 程序初始执行上下文的顶级对象。

#!/usr/bin/env ruby
puts "Hello"

回答by Alexander

There is no magic main function in Ruby. See http://en.wikipedia.org/wiki/Main_function#Ruby

Ruby 中没有神奇的 main 函数。见http://en.wikipedia.org/wiki/Main_function#Ruby

回答by Aleksander Pohl

If you wish to run Ruby scripts like C compiled files, do the following:

如果您希望像 C 编译文件一样运行 Ruby 脚本,请执行以下操作:

##代码##

and then chmod a+x file_name.rb. Everything that is below the first line will be run, as if it was contents of mainin C. Of course class and function definitions won't give you any results until they are instantiated/invoked (although the code inside class definitions is actually evaluated, so you could get some output but this is not expected in normal circumstances).

然后chmod a+x file_name.rb。第一行以下的所有内容都将运行,就好像它是mainC中的内容一样。当然,类和函数定义在实例化/调用之前不会给您任何结果(尽管实际上对类定义中的代码进行了评估,所以你可以获得一些输出,但在正常情况下这不是预期的)。