Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call ruby function from command-line

How can I directly call a ruby function from the command-line?

Imagine, I would have this script test.rb:

class TestClass     def self.test_function(some_var)         puts "I got the following variable: #{some_var}"     end end 

If this script is run from the command-line (ruby test.rb), nothing happens (as intended).

Is there something like ruby test.rb TestClass.test_function('someTextString')? I want to get the following output: I got the following variable: someTextString.

like image 536
user1251007 Avatar asked Apr 25 '12 13:04

user1251007


People also ask

How do I call a ruby function from the command-line?

With this, you can just type $ ruby test. rb and it will do what you want. Or you can chmod +x test. rb; ./test.

How do I run a ruby class from the command-line?

It's easy -- just create a file with the extension . rb , navigate to that file's directory from the command line, and run it using $ ruby filename. rb (the dollar sign is just the command prompt). You'll be able to gets from and puts to the command line now!

How do I test a ruby code in terminal?

Open a script in the editor and press ⌃⇧R / Ctrl+Shift+F10. Right-click a script in the editor or Project view and select Run 'script' from the context menu. Press Ctrl twice to invoke the Run Anything popup and execute the ruby script. rb command.


1 Answers

First the name of the class needs to start with a capital letter, and since you really want to use a static method, the function name definition needs to start with self..

class TestClass     def self.test_function(someVar)         puts "I got the following variable: " + someVar     end end 

Then to invoke that from the command line you can do:

ruby -r "./test.rb" -e "TestClass.test_function 'hi'" 

If you instead had test_function as an instance method, you'd have:

class TestClass     def test_function(someVar)         puts "I got the following variable: " + someVar     end end 

then you'd invoke it with:

ruby -r "./test.rb" -e "TestClass.new.test_function 'hi'" 
like image 154
Candide Avatar answered Nov 02 '22 23:11

Candide