2013-10-14 94 views
0

當我嘗試通過IRB加我的日期在終端:日期字符串錯誤

song.released_on = Date.new(2013,10,10) 

它說,有這個代碼以下錯誤TypeError: no implicit conversion of Date into String

def released_on=date 
    super Date.strptime(date, '%m/%d/%Y') 
end 

我已經嘗試了幾個小時知道並找不到問題。想知道有人可以幫忙嗎?

+1

什麼是你的問題? – sawa

回答

6

代碼:

def released_on=date 
    super Date.strptime(date, '%m/%d/%Y') 
end 

使用strptime(字符串分析時間)函數Date類的。它需要兩個字符串,一個代表實際日期,另一個字符串格式化程序。

所有你需要爲了把事情的工作做的是改變:

song.released_on = Date.new(2013,10,10) # Wrong, not a string! 
song.released_on = '10/10/2013' # Correct! 

你也可以改變的功能也接受日期:

def released_on=date 
    parsed_date = case date 
    when String then Date.strptime(date, '%m/%d/%Y') 
    when Date then date 
    else raise "Unable to parse date, must be Date or String of format '%m/%d/%Y'" 
    end 
    super parsed_date 
end 
1

你傳遞一個Date實例Date::strptime

date = Date.new(2013,10,10) 
Date.strptime(date, '%m/%d/%Y') #=> TypeError: no implicit conversion of Date into String 

相反,你必須通過String(使用正確的格式):

date = "10/10/2013" 
Date.strptime(date, '%m/%d/%Y') #=> Thu, 10 Oct 2013 
+0

或者讓'released_on ='巧妙地通過'Date'按原樣傳遞。 –