2012-08-28 53 views
0

試圖在.erb頁面中截斷Ruby/Sinatra中的字符串。 我一直在努力的變種:字符串操作在Sinatra/ERB中不起作用

<%= @caption_str.truncate(20) %> 
<%= @caption_str[0..20] %> 

但是要得到一種錯誤信息:

NoMethodError at /392471267473009 
undefined method `[]' for nil:NilClass 

NoMethodError at /392471267473009 
undefined method `truncate' for nil:NilClass 

一切都很好,如果我不截斷字符串,即

<%= @caption_str %> 

我錯過了什麼?

+0

我想看看關於@caption_str的代碼。也許在你的sinatra基本文件中? – halfelf

+0

謝謝@halfelf,Jatin剛到問題的核心 –

回答

1
NoMethodError at /392471267473009 
undefined method `[]' for nil:NilClass 

NoMethodError at /392471267473009 
undefined method `truncate' for nil:NilClass 

的錯誤是描述性不夠。

他們傳達有no [] or truncate method defined零:NilClass,在這種情況下,原來是你@caption_str對象。

檢查@caption_str是不是nil然後再做這些操作。當@caption_str將是,你會得到同樣的錯誤。

由於Ruby是一種動態編程語言,當值爲零時,我們往往會忘記邊緣情況。在出現類似情況時總是包括檢查。

+0

謝謝!把它在一個。是的,我忘了做零的測試。 –