我正在尝试使用以下代码在文件中接受作为终端中的参数,然后将读取该更新并使用其内容更新正文变量.如果文件没有传入,那么我想要提示用户可以输入自己的正文副本.
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
当我在没有传入文件的情况下运行程序时,我得到了这个:
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 `'
我对ruby很新,因此不是最好的.我试过交换很多东西并改变一些事情,但无济于事.我究竟做错了什么?
解决方法
定义?(ARGV)不会返回布尔值false,而是返回“常量”.由于这不会被评估为false,因此filename被定义为ARGV [0],即nil.
>> ARGV => [] >> defined?(ARGV) => "constant" ?> ARGV.first => nil
相反,你可以检查ARGV的长度:
if ARGV.length > 0 filename = ARGV.first.chomp end
defined? expression tests whether or not expression refers to anything recognizable (literal object,local variable that has been initialized,method name visible from the current scope,etc.). The return value is nil if the expression cannot be resolved. Otherwise,the return value provides information about the expression.