2016-03-19 40 views
1

我正在寫一個輔助方法,它將一個類添加到一個元素,這取決於兩個數字是否相等。我的代碼如下:比較數字意外的麻煩

<% for note in @company.convertible_notes.each %> 
    <% if note.id %> 
     <li class="tab <%= note_nav(params, note.id) %>"><%= link_to "#{note.security_series} #{note.security_class} Note", convertible_note_convertible_notees_path(note) %></li> 
    <% end %> 
<% end %> 

note_nav調用下面的幫助:

def note_nav(params, note) 
    "active" if params[:controller]=="convertible_notees" && note.to_s==params[:converible_note_id].to_s 
end 

現在令人驚訝的是,我不能表達note.to_s==params[:converible_note_id].to_s註冊真實。即使我知道被比較的兩個數字都是「1」。我檢查使用我的日誌:

logger.debug "are they equal? #{note.to_s==params[:converible_note_id].to_s} note.id is #{note} note params are #{params[:convertible_note_id]}" 

其產生以下日誌條目:

他們是平等的嗎?假note.id是1注PARAMS是1

我猜他們是兩種不同的類型,但考慮到我已經轉換他們兩個to_s的,我不知道怎麼會是一個問題。我在其他模型的幾個組合上使用了完全相同的技術,並且完全沒有錯誤。任何想法可能會發生什麼?

在此先感謝

+0

在第一種情況下,這不是一個錯字嗎?:'if params [:controller] ==「convertible_notees」' - 注意「注意事項」...這將使整個條件總是失敗... – BoraMa

+0

@borama沒有這是正確的,雖然有點怪異 – neanderslob

回答

2

看看你的測試

"are they equal? #{note.to_s==params[:converible_note_id].to_s} note.id is #{note} note params are #{params[:convertible_note_id].to_s}" 

:converible_note_id:convertible_note_id其他鍵,錯誤類型

0

你也獲取輸出,如果一個變量包含非打印字符:

note = "1\000" 

params = { 
    convertible_note_id: 1 
} 

puts "are they equal? #{note.to_s==params[:convertible_note_id].to_s}" 
puts "note.id is #{note} note params are #{params[:convertible_note_id]}" 

--output:-- 
are they equal? false 
note.id is 1 note params are 1 

要查看字符串中的真實情況,應該始終使用inspect():

p note.to_s, params[:convertible_note_id].to_s 

--output:-- 
"1\u0000" 
"1"