dennismonsewicz
dennismonsewicz

Reputation: 25542

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

Upvotes: 1

Views: 307

Answers (2)

Wally Altman
Wally Altman

Reputation: 3545

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.

Upvotes: 4

Patrick Oscity
Patrick Oscity

Reputation: 54674

How about this:

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

Upvotes: 1

Related Questions