I have a program, which calculate many things. While I run the code by ruby code.rb everything is okay. The problem starts, when I want to run it by command line with additional option: ruby code.rb --time 201712121100.
The piece of problematic code is below:
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
is just define to print messages.
mode
takes true
or false
values.
I received an error:
"
calculate_t
: undefined methodstrftime
for"201712121100":String
(NoMethodError
)"
What am I doing wrong? Why using Time.now.utc
is working while giving a specific time is not?
I also checked the solutions from here Rails undefined method `strftime' for "2013-03-06":String and Date.parse() gives the same error.
The issue is here:
time_op.pop.andand
time_op
taken from the command line is a string, and you need a Time
instance. The get it, use DateTime#strptime
:
DateTime.strptime(time_op.pop, "%Y%m%d%H%M").to_time.andand