加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

接受命令行参数到Ruby脚本

发布时间:2020-12-17 04:04:47 所属栏目:百科 来源:网络整理
导读:我正在尝试使用以下代码在文件中接受作为终端中的参数,然后将读取该更新并使用其内容更新正文变量.如果文件没有传入,那么我想要提示用户可以输入自己的正文副本. require 'posterous'Posterous.config = { 'username' = 'name','password' = 'pass','api_tok
我正在尝试使用以下代码在文件中接受作为终端中的参数,然后将读取该更新并使用其内容更新正文变量.如果文件没有传入,那么我想要提示用户可以输入自己的正文副本.

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

From the docs:

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读