Ruby / regex gets the first letter of each word

I want to get the first letter of each word put together, turning something like "I need help" into "Inh" . I thought to trim everything, then from there or immediately take every first letter.

+8
ruby regex
source share
4 answers

Here you can simply use split , map and join .

 string = 'I need help' result = string.split.map(&:first).join puts result #=> "Inh" 
+16
source share

Alternative solution using regex

 string = 'I need help' result = string.scan(/(\A\w|(?<=\s)\w)/).flatten.join puts result 

It basically says, "Look for either the first letter or any letter immediately preceding the space." The scan function returns an array of matching arrays that are flattened (made into one array) and joined (made into a string).

+1
source share
 string = 'I need help' result = string.split.map(&:chr).join puts result 

http://ruby-doc.org/core-2.0/String.html#method-i-chr

+1
source share

What about regular expressions? When using the split method, the focus is on those parts of the line that you do not need for this task, and then another step is taken to extract the first letter of each word (chr). this is why i think regular expressions are better for this case. The node that this will also work if you have - or another special character in the string. And then, of course, you can add the .upcase method at the end to get the correct abbreviation.

string = 'something - something and something else'

string.scan(/\b\w/).join

#=> ssase

+1
source share

All Articles