0

Noob question, but how do I add a command in a ruby script for the terminal?

for example ruby tool.rb and I want to add a command -c that will invoke a method that prints blah blah, and then execute it via the terminal in kali linux, so it would look something like this ruby tool.rb -c. Would anyone know how to do this and know what this is called?

HorseLeg
  • 37
  • 4

2 Answers2

0

That's called running a ruby script/program from the command line and passing "flags" like -c are passed to the script as command line arguments and are an array of string values separated by spaces normally.

Here's your very simple script:

tool.rb

#!/usr/bin/env ruby

if ARGV[0] == '-c'
  puts 'blah blah'
end

You can run this from the command line exactly as you requested.

ruby tool.rb -c

Updated

If you need additional arguments or want to pass something else to your flag you can do as I mentioned ARGV is an array constructed from string passed after the name of your ruby script so:

#!/usr/bin/env ruby

if ARGV[0] == '-c'
  puts "blah blah #{ARGV[1]}" # array items are called by index
end

So if you do this:

ruby tool.rb -c foo

You will get:

blah blah foo
lacostenycoder
  • 10,623
  • 4
  • 31
  • 48
  • Thank you, one last question how would I add a value to the called flag e.g. `-c "some string or value"`?@lacostenycoder – HorseLeg Apr 18 '19 at 18:29
  • everything after the name of your ruby script is interpreted as string input data in `ARGV` for more info see https://stackoverflow.com/questions/4244611/pass-variables-to-ruby-script-via-command-line and https://ruby-doc.org/core-1.9.3/ARGF.html – lacostenycoder Apr 18 '19 at 21:28
0

you can solve this with the help of metaprogramming and hash

def invoke
  puts "blah blah"
end

fun = {"-c": "invoke"}
send(fun[:"#{ARGV[0]}"])

in terminal

ruby tool.rb -c

send invokes private method also be cautious in using it

Hope, this is the solution you are looking for

Narayanan V
  • 31
  • 1
  • 8