简体   繁体   English

字符串比较不适用于Ruby

[英]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" ; 我检查了current_user.role.title的值,然后打印出“Test”; but when i compare it inside the html page this fails. 但是当我在html页面中进行比较时,这会失败。 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. current.role.title作为Varchar存储在数据库中。

To expand on my comment, it looks like you managed to get a trailing space in your title . 为了扩展我的评论,看起来你设法在你的title获得一个尾随空格。 You're getting -Test - when you try: 当你尝试时,你得到了-Test -

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. current_user.role.bytes.count是5所以它只是一个普通的空间(或可能是一个标签),而不是一些Unicode混淆。

You probably want to clean up your data before storing it with strip or strip! 您可能希望在使用stripstrip!存储数据之前清理数据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: 尾随空格还解释了为什么您的split方法表现如预期:

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. 只是string.split将拆分(几乎总是)拆分空格,因此role_Array最终看起来像['Test']因为split会抛弃尾随空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM