【问题标题】:Taking a specific time from command line is not working从命令行获取特定时间不起作用
【发布时间】:2018-06-03 05:26:32
【问题描述】:

我有一个程序,可以计算很多东西。当我通过 ruby​​ code.rb 运行代码时,一切正常。当我想通过带有附加选项的命令行运行它时,问题就开始了:ruby code.rb --time 201712121100。

有问题的代码如下:

include Options #here I have some options to choose, like --time

def calculate_p(time, mode)
   if mode
      calculator = calc1
   else
      calculator = calc2
   end
   calculate_t(time, calculator)
 end

def calculate_t(time, calculator)
   date_ymd = time.strftime("%Y%m%d")
   time_hm  = time.strftime("%H%M")

   calculator
     .with(date_ymd, time_hm)
   .run do |result|
      if result.ok?
         result.stdout.pop.split.first
      else
        msgw("Program returned with errors.", :error)
        msgw("stdout: %s; stderr: %s" % [result.stdout, result.stderr], :error)
        false
      end
    end
 end

time  = Options.get('--time')
           .andand do |time_op|
              msgw('Taking time from command line arguments') do
                time_op.pop.andand
              end
            end || msgw('Calculating time for now.') do
              Time.now.utc
            end || abort
calc=calculate_p(time, mode)

msgw 只是定义打印消息。

mode 采用 truefalse 值。

我收到一个错误:

calculate_t: 未定义方法strftime for "201712121100":String (NoMethodError)”

我做错了什么?为什么使用Time.now.utc 有效,而给出特定时间则无效?

我还检查了这里的解决方案Rails undefined method `strftime' for "2013-03-06":String 和 Date.parse() 给出同样的错误。

【问题讨论】:

标签: ruby strftime


【解决方案1】:

问题就在这里:

time_op.pop.andand

从命令行获取的time_op 是一个字符串,您需要一个Time 实例。得到它,使用DateTime#strptime

DateTime.strptime(time_op.pop, "%Y%m%d%H%M").to_time.andand

【讨论】:

  • 将行更改为 DateTime.strptime(time_op, "%Y%m%d%H%M").pop.and 并没有帮助。它给了我“`strptime':没有将 Array 隐式转换为 String (TypeError)”。你的例子中的 to_time 是什么?
  • 已更新。我放错了pop
  • 它适用于:ruby code.rb --time 201712121100。但有时我仍想通过 ruby​​ code.rb 在当前时间执行它,它给了我“`strptime':没有隐式转换零到字符串(类型错误)”。为什么会这样?
猜你喜欢
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 2011-08-09
  • 1970-01-01
  • 2013-06-14
  • 1970-01-01
  • 2015-10-12
  • 1970-01-01
相关资源
最近更新 更多