Search code examples
ruby-on-railsrubystringruby-on-rails-3string-comparison

String Comparison not working in Ruby


I want to compare two values given

<% if (current_user.role.title).eql?( "Test") %>

but this comparison doesn't seem to work at all. I checked for the value in current_user.role.title and it prints "Test" ; but when i compare it inside the html page this fails. I also tried doing

<% if current_user.role.title == "Test" %>

but it doesnt work!! The value current.role.title is stored as a Varchar in the database.


Solution

  • To expand on my comment, it looks like you managed to get a trailing space in your title. You're getting -Test - when you try:

    Rails.logger.error '-' + current_user.role.title + '-'
    

    and current_user.role.bytes.count is 5 so it is just a plain space (or possibly a tab) rather than some Unicode confusion.

    You probably want to clean up your data before storing it with strip or strip! and you'll want to do the same to any data you already have.

    One final check would be to try this:

    <% if current_user.role.title.strip == "Test" %>
    

    The trailing space also explains why your split approach behaved as expected:

    role_Array = (current_user.role.title).split
    if role_Array[0] != "Test"
    

    Just string.split will split (almost always) split on spaces so role_Array ended up looking like ['Test'] because split would throw away the trailing space.