Taking command line arguments in Ruby Script

I am trying to use the following code to accept in a file as an argument in a terminal, which will then be read and update the body variable with its contents. If the file is not transferred, then I want to receive an invitation in which the user can enter his own copy of the body.

 require 'posterous' Posterous.config = { 'username' => 'name', 'password' => 'pass', 'api_token' => 'token' } include Posterous @site = Site.primary #GETS POST TITLE puts "Post title: " title = STDIN.gets.chomp() if defined?(ARGV) filename = ARGV.first end if (defined?(filename)) body = File.open(filename) body = body.read() else puts "Post body: " body = STDIN.gets.chomp() end puts body 

When I run the program without transferring to the file, I return it:

 Post title: Hello posterous.rb:21:in `initialize': can't convert nil into String (TypeError) from posterous.rb:21:in `open' from posterous.rb:21:in `' 

I am new to the ruby ​​and therefore not the best at it. I tried to shift a lot of things and change things, but to no avail. What am I doing wrong?

+4
source share
2 answers

defined?(ARGV) will not return a boolean false , but rather a "constant" . Since this is not evaluated as false , filename is defined as ARGV[0] , which is nil .

 >> ARGV => [] >> defined?(ARGV) => "constant" ?> ARGV.first => nil 

Instead, you can check the length of the ARGV :

 if ARGV.length > 0 filename = ARGV.first.chomp end 

From the docs:

determined by? expression checks whether the expression refers to something recognizable (literal object, local variable that was initialized, method name is visible from the current area, etc.). The return value is zero if the expression cannot be resolved. Otherwise, the return value provides information about this expression.

+10
source
Michael gave you the basic answer to your question. A slightly more ruby ​​way to do this is to use ARGF for reading; This condition is only necessary in order to decide whether to print out the invitation:
 puts "Post title: " title = gets.chomp puts "Post body: " if ARGV.length == 0 body = ARGF.gets.chomp puts body 

.. of course, if you do not need anything with the body, you can skip saving the contents of the file (s) and just do

 puts ARGF.gets.chomp 
+2
source

Source: https://habr.com/ru/post/1403749/


All Articles