简体   繁体   English

ROR +通过使用红宝石代码检测另一个字符来替换最后一个字符

[英]ROR + Replace the last character by detecting it using ruby code by another character

Is it possible to detect the last character of string in ruby on rails and replace it by "". 是否有可能在ruby上检测到字符串的最后一个字符并将其替换为“”。 Explanation :: Suppose I have string as "demo-" then i have to check its last character, If it is "-" then replace it by "", otherwise no action should be taken. 说明::假设我的字符串为“ demo-”,那么我必须检查其最后一个字符;如果为“-”,则将其替换为“”,否则不采取任何措施。

Example - Code :: 示例-代码::

search_text.downcase! if !search_text.nil?

now if seach_text have value as "demo-" then change it to "demo" by replacing "-". 现在,如果seach_text的值为“ demo-”,则通过替换“-”将其更改为“ demo”。

Thanks in Advance !!! 提前致谢 !!!

Much simpler: 简单得多:

text.chomp!('-')

chomp already includes the if condition: if the character exists at the end of the string, it is removed. chomp已经包含了if条件:如果字符存在于字符串的末尾,则将其删除。

> a = "abc-"
=> "abc-"
>> a.chop! if a[-1] == 45 # if last character is a minus sign chop it off
=> 45
>> a
=> "abc"

try the following 尝试以下

text.chop! if text[text.length-1,1] == "-"

text.chop! text.chop! removes the last character and saves it to the same object 删除最后一个字符并将其保存到同一对象

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

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