Alex Rivera | Logout

Call a Ruby function from the command line

Asked 2012-04-25T13:17:02.297
56

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.

Edit
Report

1 Answer

4

Just an extension to Ingenu's answer for the case that the function does not print something out, but does return something.

We would have the following test.rb

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

Then to invoke that from the command line and get the return value:

ruby -r "./test.rb" -e "puts TestClass.test_function('hi')"
answered 2012-04-25T21:19:30.050

Your Answer