我有一个开始月(3),开始年(2004年),我有一个结束年(2008年)。我想计算开始日期和结束日期之间的单词时间。这就是我正在尝试的,它不起作用..
# first want to piece the start dates together to make an actual date
# I don't have a day, so I'm using 01, couldn't work around not using a day
st = (start_year + "/" + start_month + "/01").to_date
ed = (end_year + "/01/01").to_date
# the above gives me the date March 1st, 2004
# now I go about using the method
distance_of_time_in_words(st, ed)
..这会抛出一个错误,“字符串不能强迫我进入fixnum”。有人见过这个错误吗?
答案 0 :(得分:1)
你不能只在Ruby中连接字符串和数字。您应该将数字转换为字符串,建议使用 mliebelt ,或者像这样使用string interpolation:
st = "#{start_year}/#{start_month}/01".to_date
但是对于你的特殊情况,我认为根本不需要字符串。你可以这样做:
st = Date.new(start_year, start_month, 1)
ed = Date.new(end_year, 1, 1)
distance_of_time_in_words(st, ed)
甚至是这样:
st = Date.new(start_year, start_month)
ed = Date.new(end_year)
distance_of_time_in_words(st, ed)
有关详情,请参阅Date
班级docs。
答案 1 :(得分:0)
鉴于您调用该方法的上下文是知道来自ActionView::Helpers::DateHelper
的方法的上下文,您应该更改以下内容:
# first want to piece the start dates together to make an actual date
# I don't have a day, so I'm using 01, couldn't work around not using a day
st = (start_year.to_s + "/" + start_month.to_s + "/01").to_date
ed = (end_year.to_s + "/01/01").to_date
# the above gives me the date March 1st, 2004
# now I go about using the method
distance_of_time_in_words(st, ed)
=> "almost 3 years"
所以我已经为to_s
添加了对号码的调用,以确保操作+
正常运行。可能有更有效的方法来构建日期,但你的日期已经足够了。