简体   繁体   English

Ruby:在最后一个数字字符上分割字符串

[英]Ruby: Splitting string on last number character

I have the following method in my Ruby model: 我的Ruby模型中有以下方法:

Old: 旧:

def to_s
    numbers = self.title.scan(/\d+/) if self.title.scan(/\d+/)
    return numbers.join.insert(0, "#{self.title.chop} ") if numbers

    "#{self.title.titlecase}"
  end

New: 新:

def to_s
    numbers = self.title.scan(/\d+/)
    return numbers.join.insert(0, "#{self.title.sub(/\d+/, '')} ") if numbers.any?

    self.title.titlecase
  end

A title can be like so: Level1 or TrackStar title可以像这样:Level1或TrackStar

So TrackStar should become Track Star and Level1 should be come Level 1, which is why I am doing the scan for numbers to begin with 因此,TrackStar应该成为Track Star,Level1应该成为Level 1,这就是为什么我要扫描数字开头的原因

I am trying to display it like Level 1. The above works, I was just curious to know if there was a more eloquent solution 我试图将其显示为第1级。上面的作品,我只是想知道是否有更雄辩的解决方案

Try this: 尝试这个:

def to_s
  self.title.split(/(?=[0-9])/, 2).join(" ")
end

The second argument to split is to make sure a title like "Level10" doesn't get transformed into "Level 1 0". split的第二个参数是确保不会将“ Level10”之类的标题转换为“ Level 1 0”。

Edit - to add spaces between words as well, I'd use gsub : 编辑 -在单词之间也添加空格,我会使用gsub

def to_s
  self.title.gsub(/([a-z])([A-Z])/, '\1 \2').split(/(?=\d)/, 2).join(" ")
end

Be sure to use single-quotes in the second argument to gsub . 确保在gsub的第二个参数中使用单引号。

How about this: 这个怎么样:

'Level1'.split(/(\d+)/).join(' ')
#=> "Level 1"

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

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