有条件地格式化记录轨道的方法中的正则表达式4(regular expression in method to conditionally format record rails 4)

编程入门 行业动态 更新时间:2024-10-26 02:32:03
有条件地格式化记录轨道的方法中的正则表达式4(regular expression in method to conditionally format record rails 4)

我正在尝试有条件地在开头设置一个带有“The”的名称格式。 我的正则表达式有效,但我不知道如何使它成为一个条件语句(基本上如果这个记录在开头包含一个“the”,那么“do splitting”。当我显示一个巨大的数据表时,我我希望保持这种效率。

Class Contact < ActiveRecord::Base def adjusted_name if "name LIKE ?", 'The%' set_name = self.name.split('The ')[1] self.name = format('%s, The', set_name) end end end

I'm trying to conditionally set a format of names with a "The" at the beginning. My regular expression works, but I don't know how to make it a conditional statement (basically if this record contains a "the" at the beginning, then "do splitting". As I'm showing a huge table of data, I'd like to keep this efficient.

Class Contact < ActiveRecord::Base def adjusted_name if "name LIKE ?", 'The%' set_name = self.name.split('The ')[1] self.name = format('%s, The', set_name) end end end

最满意答案

带正则表达式的gsub应该可以解决这个问题:

def adjusted_name self.name = name.gsub(/^The (.*)$/, '\1, The') end

gsub with a regex should do the trick:

def adjusted_name self.name = name.gsub(/^The (.*)$/, '\1, The') end

更多推荐

本文发布于:2023-04-28 03:19:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1329832.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有条件   轨道   方法   正则表达式   regular

发布评论

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

>www.elefans.com

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