Getting Input from Command-Line Arguments

Input isn’t always interactive. The rapid start-up of compiled Crystal code makes it an excellent fit for command-line applications. What if you need to supply the program with data or options from the command line?

For example, let’s read in two currencies and their relative rate (1 USD = 0.8432053 EUR today): $ crystal argv.cr USD EUR 0.84320536

Crystal, like Ruby, has the top-level ARGV structure to handle this:

 puts ​"Number of command line arguments: ​​#{​ARGV.​size​​}​​"​ ​# => (1)
 ARGV.​each_with_index​ ​do​ |arg, i|
  puts ​"Argument ​​#{​i​}​​: ​​#{​arg​}​​"​ ​# => (2)
 end
 p ARGV ​# => (3)
 p ​"Executable name: ​​#{​PROGRAM_NAME​}​​"​ ​# => (4)
 p ​"Path to source file: ​​#{​​__FILE__​​}​​"​ ​# => (5)
 p ​"Folder of source file: ​​#{​__DIR__​}​​"​ ​# => (6)
 
 # (1) Number of command line arguments: 3
 # (2)
 # Argument 0: USD
 # Argument 1: EUR
 # Argument 2: 0.84320536
 # # (3) ["USD", "EUR", "0.84320536"]
 # (4) "Executable name: /$HOME/.cache/crystal/crystal-run-argv.tmp"
 # or (4) "Executable name: ./argv"
 # (5) "Path to source file:
 # /$HOME/crystal/Book/code/types_and_control_flow/argv.cr"
 # (6) "Folder of source file:
 # /$HOME/crystal/Book/code/types_and_control_flow"

You can run through ARGV as an array with each or each_with_index and use the do-block for whatever you want to do with the arguments. Here’s a more realistic example: if you start up a program, db_json, like this: $ ./db_json sqlite3://db/sqlite3.db, then ARGV[0] contains the database connection string.

Your code has access to the executable name as the constant PROGRAM_NAME. This is "./argv" if you generated an executable with $ crystal build program.cr. When you start it like $ crystal program.cr , you’ll see that the executable is created in a special .cache/crystal folder. Here, all compiler intermediary files (such as macro expansions, linker .o files, temporary files from the playground, and so on) are saved.

__FILE__ and __DIR__

images/aside-icons/tip.png

__FILE__ is a special constant that contains the complete path to the current file name. __DIR__ contains the directory of the current file.

Here’s a version of our currency converter that reads in the base currency from the command line when starting the program like $ ./curr_conv3 EUR:

 base = ARGV[0]?
 base = ​"USD"​ ​unless​ base
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.152.139