Call a Ruby function from the command line

command-line, ruby

Solution

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'"

Problem

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`.

Original source