我有一个计算很多东西的程序。虽然我通过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
采用true
或false
值。
我收到一个错误:
“
calculate_t
:未定义的方法strftime
为"201712121100":String
(NoMethodError
)”
我究竟做错了什么?为什么使用Time.now.utc
工作,而给出一个特定的时间不是?
我还从这里检查了解决方案Rails undefined method `strftime' for "2013-03-06":String和Date.parse()给出了同样的错误。
问题在于:
time_op.pop.andand
从命令行获取的time_op
是一个字符串,你需要一个Time
实例。得到它,使用DateTime#strptime
:
DateTime.strptime(time_op.pop, "%Y%m%d%H%M").to_time.andand