Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 718
bastibe Avatar asked Oct 22 '10 13:10

bastibe


People also ask

How do you split a string in Ruby?

split is a String class method in Ruby which is used to split the given string into an array of substrings based on a pattern specified. Here the pattern can be a Regular Expression or a string. If pattern is a Regular Expression or a string, str is divided where the pattern matches.

How do you split a string into an array in Ruby?

The general syntax for using the split method is string. split() . The place at which to split the string is specified as an argument to the method. The split substrings will be returned together in an array.


2 Answers

s = 'nowIsTheTime'  s.split /(?=[A-Z])/  => ["now", "Is", "The", "Time"] 

?=pattern is an example of positive lookahead. It essentially matches a point in the string right before pattern. It doesn't consume the characters, that is, it doesn't include pattern as part of the match. Another example:

    irb> 'streets'.sub /t(?=s)/, '-' => "stree-s" 

In this case the s is matched (only the second t matches) but not replaced. Thanks to @Bryce and his regexp doc link. Bryce Anderson adds an explanation:

The?=at the beginning of the()match group is called positive lookahead, which is just a way of saying that while the regex is looking at the characters in determining whether it matches, it's not making them part of the match. split()normally eats the in-between characters, but in this case the match itself is empty, so there's nothing [there].

like image 69
DigitalRoss Avatar answered Oct 18 '22 17:10

DigitalRoss


I know this is old, but worth mentioning for others who might be looking for this. In rails you could do this: "NowIsTheTime".underscore.humanize

like image 39
Fitmo Appadmin Avatar answered Oct 18 '22 17:10

Fitmo Appadmin