How to split a CamelCase string in its substrings in Ruby?

Viewed 16238

I have a nice CamelCase string such as ImageWideNice or ImageNarrowUgly. Now I want to break that string in its substrings, such as Image, Wide or Narrow, and Nice or Ugly.

I thought this could be solved simply by

camelCaseString =~ /(Image)((Wide)|(Narrow))((Nice)|(Ugly))/

But strangely, this will only fill $1 and $2, but not $3.

Do you have a better idea for splitting that string?

8 Answers
I/p:- "ImageWideNice".scan(/[A-Z][a-z]+/).join(",")

O/p:- "Image,Wide,Nice"
def solution(string)
  final_str = []
  string.chars.each do |x|
    final_str << " "  if x.upcase == x 
    final_str << x
  end
  final_str.join
end
Related