简体   繁体   中英

Ruby: Splitting string on last number character

I have the following method in my Ruby model:

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

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

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

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".

Edit - to add spaces between words as well, I'd use 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 .

How about this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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