ruby/regex getting the first letter of each word

How about regular expressions? Using the split method here forces a focus on the parts of the string that you don't need to for this problem, then taking another step of extracting the first letter of each word (chr). that's why I think regular expressions is better for this case. Node that this will also work if you have a - or another special character in the string. And then, of course you can add .upcase method at the end to get a proper acronym.

string = 'something - something and something else'

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

#=> ssase


Alternative solution using regex

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

puts result

This basically says "look for either the first letter or any letter directly preceded by a space". The scan function returns array of arrays of matches, which is flattened (made into one array) and joined (made into a string).


You could simply use split, map and join together here.

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

Tags:

Ruby

Regex