字符串比较在 Ruby 中不起作用 [英] String Comparison not working in Ruby

查看:41
本文介绍了字符串比较在 Ruby 中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想比较给定的两个值

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

但这种比较似乎根本不起作用.我检查了 current_user.role.title 中的值,它打印了 "Test" ;但是当我在 html 页面中比较它时,这失败了.我也试过

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" %>

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

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

推荐答案

为了扩展我的评论,您似乎设法在 title 中添加了尾随空格.当您尝试时,您将获得 -Test -:

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 + '-'

current_user.role.bytes.count 是 5,所以它只是一个普通的空格(或者可能是一个制表符)而不是一些 Unicode 混淆.

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

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

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" %>

尾随空格还解释了为什么您的 split 方法按预期运行:

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

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

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

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.

这篇关于字符串比较在 Ruby 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆