43

私はRubyを初めて使用するので、これが本当にばかげているように聞こえたらお詫びします。

「メイン」コードを記述し、同じファイルにメソッドを含める方法がわからないようです(Cと同様)。最終的に、すべてのメソッドを含む個別のファイルをロードする「メイン」ファイルになります。これに関するガイダンスに感謝します。

次のSO投稿を見つけましたが、理解できません 。rubyスクリプトでmainメソッドを定義する必要がありますか?

大したことではありませんが、同じファイル内の関連するすべてのコードを表示できる方が簡単です。ありがとうございました。

[-編集-]

回答してくれたすべての人に感謝します-コードの上にあるすべてのメソッドを定義するだけでよいことがわかりました。例を以下に示します。

def callTest1
    puts "in test 1"
end

def callTest2
    puts "in test 2" 
end

callTest1
callTest2

Rubyはすべてのメソッドを事前に知っている必要があるため、これは理にかなっていると思います。これは、使用可能な関数を明確にリストするヘッダーファイルがあり、したがってmain()関数の下にそれらを定義できるCとは異なります。

繰り返しになりますが、回答してくれたすべての人に感謝します。

4

6 に答える 6

42

@Haulethの答えは正解です。Rubyにはmainメソッドや構造はありません。ここでは、少し異なる見方と説明を提供したいと思います。

を実行するruby somefile.rbと、Rubyは内のすべてのコードを実行しsomefile.rbます。したがって、非常に小さなプロジェクトがあり、それを1つのファイルに自己完結させたい場合は、次のようなことをしてもまったく問題はありません。

# 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

最初の2つのブロックが実行されないのではなく、対応するクラス/メソッドを実際に使用するまで効果が表示されないだけです。

このif __FILE__ == $0ビットは、このファイルがコマンドラインから直接実行されている場合にのみ実行するコードをブロックする方法にすぎません。 __FILE__ は現在のファイルの名前であり$0、シェルによって実行されたコマンドです(ただし、を削除するのに十分賢いですruby)。したがって、2つを比較すると、次のことが正確にわかります。これはコマンドラインから実行されたファイルですか。これは、ファイルにクラス/モジュールを定義し、それを使用するコマンドラインユーティリティを提供したいコーダーによって行われることがあります。IMHOはあまり良いプロジェクト構造ではありませんが、他のプロジェクトと同じように、それを実行することが完全に理にかなっているユースケースがあります。

コードを直接実行できるようにしたい場合は、シバン行を追加できます

#!/usr/bin/env ruby

# rest of somefile.rb

そしてそれを実行可能にしますchmod +x somefile.rb(オプションで.rb拡張子なしで名前を変更します)。これは実際には状況を変えません。if __FILE__ == $0それでも機能し、おそらく必要ありません。

編集

@steenslagが正しく指摘しているように、Rubyの最上位スコープはObjectと呼ばれmainます。ただし、少しファンキーな動作があります。

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

言語をさらに深く掘り下げ始めるまで、これについて心配する必要はありません。この種のことについてもっと多くを学びたいのであれば、 Rubyのメタプログラミングは素晴らしい読み物です:)

于 2012-03-13T16:16:46.673 に答える
28

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:

puts 'Hello World'

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

if __FILE__ == $0
  # 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.

于 2012-03-13T15:38:27.543 に答える
6

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.

class Foo
  p self
end
#=> Foo

p self
#=> main

def foo 
  p self
end
foo
#=> main
于 2012-03-13T21:07:16.067 に答える
1

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

于 2012-03-13T15:38:56.190 に答える
1

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

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

and then chmod a+x file_name.rb. Everything that is below the first line will be run, as if it was contents of main in 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).

于 2012-03-13T16:11:56.200 に答える
0

Another way to write main() method is:

class HelloWorld
    def initialize(name)
        @name = name
    end

    def sayHello()
        print "Hello #@name!"
    end
end

def main()
    helloWorld = HelloWorld.new("Alice")
    helloWorld.sayHello
end

main


于 2021-05-17T06:15:06.210 に答える