有条件地格式化记录轨道的方法中的正则表达式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 endI'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') endgsub with a regex should do the trick:
def adjusted_name self.name = name.gsub(/^The (.*)$/, '\1, The') end更多推荐
发布评论