Natalia Natalia -3 years ago 83
Ruby Question

How do I extract the part of a string whose individual words begin with letters?

I'm using Ruby 2.4. Let's say I have a string that has a number of spaces in it

str = "abc def 123ffg"

How do I capture all the consecutive words at the beginning of the string that begin with a letter? So for example, in the above, I would want to capture

"abc def"

And if I had a string like

"aa22 b cc 33d ff"

I would want to capture

"aa22 b cc"

but if my string were

"66dd eee ff"

I would want to return nothing because the first word of that string does not begin with a letter.

Answer Source

If you can spare the extra spaces between words, you could then split the string and iterate the resulting array with take_while, using a regex to get the desired output; something like this:

str = "abc def 123ffg"
str.split.take_while { |word| word[0] =~ /[[:alpha:]]/ }
#=> ["abc", "def"]

The output is an array, but if a string is needed, you could use join at the end:

str.split.take_while { |word| word[0] =~ /[[:alpha:]]/ }.join(" ")
#=> "abc def"

More examples:

"aa22 b    cc 33d  ff".split.take_while { |word| word[0] =~ /[[:alpha:]]/ }
#=> ["aa22", "b", "cc"]

"66dd eee ff".split.take_while { |word| word[0] =~ /[[:alpha:]]/ }
#=> []
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download