字符串比较不适用于Ruby

问题描述 投票:1回答:1

我想比较给出的两个值

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

但这种比较似乎根本不起作用。我检查了current_user.role.title中的值并打印出“Test”;但是当我在html页面中进行比较时,这会失败。我也尝试过

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

但它不起作用!!值current.role.title作为Varchar存储在数据库中。

ruby-on-rails ruby string ruby-on-rails-3 string-comparison
1个回答
4
投票

为了扩展我的评论,看起来你设法在你的title中获得一个尾随空格。当你尝试时,你得到-Test -

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

current_user.role.bytes.count是5所以它只是一个普通的空间(或可能是一个标签),而不是一些Unicode的混乱。

您可能希望在使用stripstrip!存储数据之前清理数据,并且您希望对已有的任何数据执行相同操作。

最后一次检查是试试这个:

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

尾随空格还解释了为什么你的split方法表现如预期:

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

只是string.split将分裂(几乎总是)分裂在空间上,所以role_Array最终看起来像['Test']因为split会扔掉尾随空间。

© www.soinside.com 2019 - 2024. All rights reserved.