Reputation: 2693
I'm writing a helper method that adds a class to an element depending on whether two numbers are equal to eachother. My code is as follows:
<% 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 calls the following helper:
def note_nav(params, note)
"active" if params[:controller]=="convertible_notees" && note.to_s==params[:converible_note_id].to_s
end
Now the surprising thing is that I cannot get the expression note.to_s==params[:converible_note_id].to_s
to register true. Even when I know the two numbers being compared are both "1". I checked it using my log:
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]}"
Which yields the following log entry:
are they equal? false note.id is 1 note params are 1
I would guess that they're two different types but given that I've converted both of them to_s
, I don't know how that would be an issue. I've used this exact same technique on a few combinations of other models and have been completely error free. Any idea as to what might be going on?
Thanks in advance
Upvotes: 1
Views: 52
Reputation: 48599
You could also get that output if one of the variables contains non-printing characters:
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
To see what's really in a string, you should always use inspect():
p note.to_s, params[:convertible_note_id].to_s
--output:--
"1\u0000"
"1"
Upvotes: 0
Reputation: 42182
Look at your test
"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
and :convertible_note_id
are other keys, a type error
Upvotes: 2