Call ruby function from command-line
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 endend
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 endend
then you'd invoke it with:
ruby -r "./test.rb" -e "TestClass.new.test_function 'hi'"
Here's another variation, if you find that typing ruby syntax at the command line is awkward and you really just want to pass args to ruby. Here's test.rb:
#!/usr/bin/env rubyclass TestClass def self.test_function(some_var) puts "I got the following variable: #{some_var}" endendTestClass.test_function(ARGV[0])
Make test.rb executable and run it like this:
./test.rb "Some Value"
Or run it like this:
ruby test.rb "Some Value"
This works because ruby automatically sets the ARGV
array to the arguments passed to the script. You could use ARGV[0]
or ARGV.first
to get the first argument, or you could combine the args into a single string, separated by spaces, using ARGV.join(' ')
.
If you're doing lots of command-line stuff, you may eventually have a use for Shellwords, which is in the standard ruby lib.
If you have multiple arguments to call in a example like this:
class TestClass def self.test_function(some_var1, some_var2) puts "I got the following variables: #{some_var1}, #{some_var2}" endend
run it like this (the arguments need to be comma separated in this case)
ruby -r "./test.rb" -e "TestClass.new.test_function 'hi','Mike'"