rubymethodscommand-lineoptionparser

Use a command line option to call a method


So I guess this is kind of related to my last question, but I was wondering if there was a way to call a method by using a command line option. Say you had a method like this:

def b
puts "Hello brian"
end

is there a way to write something like this:

ruby mine.rb -b 

and get this

Hello brian

I already tried looking for this online and discovered OptionParser but I have yet to discover anything involving the OptionParser calling a method previously created.


Solution

  • There are a lot of ways to do this, depending on the use case. The below code is taken from the Ruby docs with the extra method added.

    Realistically you'd probably want a class that handles the different options and encapsulates the method instead of having them at the file scope.

    #!/usr/bin/env ruby
    
    require 'optparse'
    
    options = {}
    OptionParser.new do |opts|
      opts.banner = "Usage: example.rb [options]"
    
      opts.on("-b", "Run method 'b'") do |v|
        options[:b] = true
      end
    end.parse!
    
    def b
      puts "Hello Brian"
    end
    
    if options[:b]
      b
    end
    

    I've also added a shebang at the top that will automatically call ruby. As long as your script file is executable you can call it directly (ie. ./mine.rb -b).