字符串比较在 Ruby 中不起作用
我想比较给定的两个值
<% if (current_user.role.title).eql?( "Test") %>
,但这种比较似乎根本不起作用。我检查了 current_user.role.title
中的值,它打印出“Test”;但是当我在 html 页面中比较它时,就会失败。我也尝试过,
<% if current_user.role.title == "Test" %>
但是没用!!值 current.role.title
以 Varchar 形式存储在数据库中。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为了扩展我的评论,看起来您设法在
title
中获得尾随空格。当你尝试时,你会得到-Test -
:并且
current_user.role.bytes.count
是 5,所以它只是一个普通的空格(或可能是一个制表符)而不是一些 Unicode 混乱。您可能想在使用
strip 存储数据之前清理数据
或剥离!
并且您需要对已有的任何数据执行相同的操作。
最后一项检查是尝试以下操作:
尾随空格还解释了为什么您的
split
方法的行为符合预期:仅
string.split
会(几乎总是)在空格上拆分,因此role_Array
最终看起来像['Test']
因为split
会丢弃尾部空格。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: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
orstrip!
and you'll want to do the same to any data you already have.One final check would be to try this:
The trailing space also explains why your
split
approach behaved as expected:Just
string.split
will split (almost always) split on spaces sorole_Array
ended up looking like['Test']
becausesplit
would throw away the trailing space.