Methods and Best Practices for Passing Variables to Ruby Scripts via Command Line

Nov 22, 2025 · Programming · 9 views · 7.8

Keywords: Ruby | Command Line Arguments | ARGV | OptionParser | Automation Scripts

Abstract: This article provides an in-depth exploration of various methods for passing variables to Ruby scripts via the command line, focusing on the basic usage of the ARGV array and its applications in automation scripts. It also compares the advanced features of the OptionParser library and integrates YAML configuration files to separate data from code, offering complete code examples and practical scenario analyses to help developers efficiently handle batch tasks.

Introduction

In automated script development, passing variables via the command line is a crucial technique for flexible configuration and batch processing. Ruby, as a powerful scripting language, offers multiple ways to handle command-line arguments. Based on actual Q&A data, this article delves into the usage of the ARGV array in Ruby and extends the discussion to the combined application of the OptionParser library and YAML configuration files, enhancing script maintainability and automation capabilities.

Basic Usage of the ARGV Array

In Ruby, ARGV is a global array that stores arguments passed via the command line. Each argument is stored as a string and can be accessed by index. For example, writing the following code in a script:

ARGV.each do |a|
  puts "Argument: #{a}"
end

When running the script with ./test.rb "test1 test2", the output will display each argument. This method is straightforward and suitable for scenarios with a fixed number of simple structured arguments. In the IMAP Sync example, if source and destination server connection details need to be passed, variables can be directly retrieved using ARGV[0] to ARGV[n], enabling automated batch account synchronization.

Advanced Argument Parsing with the OptionParser Library

For complex command-line interfaces, Ruby's OptionParser library offers more powerful parsing capabilities. It supports flags, switches, optional or required parameter values, and can automatically generate help information. Here is an example integrated with a YAML configuration file:

require 'optparse'
require 'yaml'

options = {}
OptionParser.new do |opts|
  opts.banner = "Usage: example.rb [options]"
  opts.on('-n', '--sourcename NAME', 'Source name') { |v| options[:source_name] = v }
  opts.on('-h', '--sourcehost HOST', 'Source host') { |v| options[:source_host] = v }
  opts.on('-p', '--sourceport PORT', 'Source port') { |v| options[:source_port] = v }
end.parse!

dest_options = YAML.load_file('destination_config.yaml')
puts dest_options['dest_name']

This approach allows static configurations, such as destination server information, to be stored in a YAML file, while dynamic parameters are passed via the command line, achieving separation of data and code. Example YAML file:

--- 
dest_name: username@gmail.com
dest_host: imap.gmail.com
dest_port: 993
dest_ssl: true
dest_user: username@gmail.com
dest_pass: password

Practical Applications and Automation Scenarios

In the IMAP Sync script, using command-line variables can significantly improve efficiency when handling hundreds of accounts. For instance, by iterating through ARGV parameters, source and destination server connection details can be set dynamically, avoiding manual code modifications. Drawing an analogy from the referenced article on Python, Ruby's ARGV is similar to Python's sys.argv, but Ruby's OptionParser offers richer parsing options. Practice shows that for simple tasks, directly using ARGV is efficient enough, while for scenarios requiring complex validation and help documentation, OptionParser is the better choice.

Conclusion

This article systematically introduces methods for passing variables to Ruby scripts via the command line, from basic ARGV usage to advanced combinations of OptionParser and YAML configurations. Developers should choose the appropriate method based on specific needs: use ARGV for quick implementation in simple scripts, and prefer OptionParser for complex applications to enhance maintainability. These techniques are not only applicable to batch tasks like IMAP synchronization but can also be extended to other automation scenarios, supporting efficient software development.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.