字符串比较在 Ruby 中不起作用

编程入门 行业动态 更新时间:2024-10-28 02:20:24
本文介绍了字符串比较在 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.

您可能希望在使用 strip 或 strip! 并且您将希望对您已有的任何数据执行相同操作.

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 中不起作用

本文发布于:2023-10-28 13:10:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1536725.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   中不   Ruby

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!