2017-02-19 78 views
0

的隱式轉換,我有一些非常基本的代碼:類型錯誤:水豚:: ElementNotFound成字符串

def select_author_name(comment) 
    selector = 'span.name' 
    comment.find(selector).text 
    rescue Capybara::ElementNotFound => e 
    Rails.logger.warn('Could not get author_name: ' + e) 
    puts e 
    '' 
    end 

當我運行這段代碼,併成功救出Capybara::ElementNotFound錯誤將其與下面的錯誤炸燬:

TypeError: no implicit conversion of Capybara::ElementNotFound into String

奇怪的是,puts e行會打印出錯誤沒有問題。

我的問題是這樣的:

爲什麼會串聯企圖引起問題的打印e時,我可以成功地與puts打印出來e?他們兩個都不會導致.to_s在封面下的通話?

回答

1

Ruby在連接字符串時實際使用隱式#to_str方法,而不是#to_s

在這種情況下,最簡單的解決方案可能是你的代碼更改爲:

Rails.logger.warn('Could not get author_name: ' + e.to_s)

如果你想避免這種出於某種原因,並寧願所有的錯誤對象的行爲與您預期時在未來做字符串連接,你也可以打通StandardError類,並定義to_str

class StandardError 
    def to_str 
    self.to_s 
    end 
end 
+0

這說明to_s'和'to_str''之間的區別:http://marcgg.com/blog/2017/ 01/23/ruby​​-to-s-to-str /。謝謝你的回答! –