【问题标题】:Accepting Command-Line Arguments into a Ruby Script将命令行参数接受到 Ruby 脚本中
【发布时间】:2012-04-11 11:02:12
【问题描述】:

我正在尝试使用以下代码在终端中接受文件作为参数,然后将读取该文件并使用其内容更新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

当我在不传递文件的情况下运行程序时,我会得到这个返回:


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​​ 比较陌生,因此不是最擅长的。我试过交换很多东西并改变东西,但无济于事。我做错了什么?

【问题讨论】:

    标签: ruby command-line-arguments posterous


    【解决方案1】:

    defined?(ARGV) 不会返回布尔值 false,而是返回 "constant"。因为这不等于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:

    定义? expression 测试 expression 是否引用任何可识别的内容(文字对象、已初始化的局部变量、从当前范围可见的方法名称等)。如果无法解析表达式,则返回值为 nil。否则,返回值提供有关表达式的信息。

    【讨论】:

      【解决方案2】:

      Michael 为您的问题提供了基本答案。一个稍微有点 Rubyish 的方法是使用 ARGF 来读取;那么只需要条件来决定是否打印提示:

      puts "Post title: "
      title = gets.chomp
      
      puts "Post body: " if ARGV.length == 0
      body = ARGF.gets.chomp
      puts body
      

      ..当然,如果您不需要任何其他内容,您可以跳过存储文件的内容而直接执行

      puts ARGF.gets.chomp
      

      【讨论】:

        猜你喜欢
        • 2012-10-07
        • 2016-08-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-12
        • 1970-01-01
        • 2012-07-19
        相关资源
        最近更新 更多