コマンドラインからRuby関数を呼び出す
概要
コマンドラインから Ruby 関数を直接呼び出すにはどうすればよいですか?
次のスクリプト test.rb があると想像してください。
class TestClass
def self.test_function(some_var)
puts "I got the following variable: #{some_var}"
end
end
このスクリプトをコマンド ライン (ruby test.rb) から実行すると、(意図したとおり) 何も起こりません。
Ruby test.rb TestClass.test_function(‘someTextString’) のようなものはありますか?
次の出力を取得したいです。次の変数を取得しました: someTextString。
解決策
まず、クラス名は大文字で始める必要があります。また、実際には静的メソッドを使用したいため、関数名の定義は self. で始まる必要があります。
class TestClass
def self.test_function(someVar)
puts "I got the following variable: " + someVar
end
end
次に、コマンドラインからそれを呼び出すには、次のようにします。
ruby -r "./test.rb" -e "TestClass.test_function 'hi'"
代わりにインスタンス メソッドとして test_function を使用した場合は、次のようになります。
class TestClass
def test_function(someVar)
puts "I got the following variable: " + someVar
end
end
次に、次のように呼び出します。
ruby -r "./test.rb" -e "TestClass.new.test_function 'hi'"