简体   繁体   中英

ArgumentError creating instance of Time class on Ruby version 1.8.6

I'm trying to get the time value using datetime_select from the view, return values obtained are:

"scheduletime"=>{"scheduletime(1i)"=>"2014", "scheduletime(2i)"=>"1", "scheduletime(3i)"=>"9", "scheduletime(4i)"=>"10", "scheduletime(5i)"=>"33"}

In controller I'm trying to create the instance of Time class using the return values of datetime_select. In following manner.

schedule_time = Time.new(params[:scheduletime]["scheduletime(1i)"], params[:scheduletime]["scheduletime(2i)"], params[:scheduletime]["scheduletime(3i)"], params[:scheduletime]["scheduletime(4i)"], params[:scheduletime]["scheduletime(5i)"],0, "+09:00")

Trying this I'm getting following error.

ArgumentError (wrong number of arguments (7 for 0))

The version of ruby I'm using is 1.8.6 . Can any one suggest me where I'm going wrong.

Time.new in Ruby 1.8.6 did not allowed any param. See the official documentation .

a = Time.new      #=> Wed Apr 09 08:56:03 CDT 2003
b = Time.new      #=> Wed Apr 09 08:56:03 CDT 2003
a == b            #=> false
"%.6f" % a.to_f   #=> "1049896563.230740"
"%.6f" % b.to_f   #=> "1049896563.231466"

My suggestion is to use Time.utc in order to create a date with given params.

You can rewrite the code using Hash#valutes_at

Time.utc(*params[:scheduletime].values_at(%w( scheduletime(1i) scheduletime(2i) scheduletime(3i) scheduletime(4i) scheduletime(5i) )))

Note that Time.utc also accepts an optional time zone (given I see you are passing one).


As a side note, you definitely need to upgrade your Ruby version.

The documentation seems to point that you can't pass arguments to the Time.new method.

Try this instead (will use your current TimeZone):

schedule_time = Time.local(params[:scheduletime]["scheduletime(1i)"], params[:scheduletime]["scheduletime(2i)"], params[:scheduletime]["scheduletime(3i)"], params[:scheduletime]["scheduletime(4i)"], params[:scheduletime]["scheduletime(5i)"],0)

# some variants, using standard TimeZone:
Time.utc(2000,"jan",1,20,15,1)  #=> Sat Jan 01 20:15:01 UTC 2000
Time.gm(2000,"jan",1,20,15,1)   #=> Sat Jan 01 20:15:01 UTC 2000
Time.local(2000,"jan",1,20,15,1)   #=> Sat Jan 01 20:15:01 CST 2000

You might want to set the TimeZone to a different one after that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM