String Comparison not working in Ruby

爷,独闯天下 提交于 2019-12-11 11:11:17

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/7857779/string-comparison-not-working-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!