Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract first letters of words in a string in ruby without looping?

Tags:

string

ruby

I have tried to get first letters of words of a string using ruby. the following is what i have written.

puts "world is a better place".split.collect{|w| w[0].capitalize}.join()

Is there a much more concise way of producing the same result?

like image 776
MIdhun Krishna Avatar asked Nov 30 '25 20:11

MIdhun Krishna


1 Answers

Using regular expression:

"world is a better place".scan(/\b[a-z]/i).join
# => "wiabp"
"world is a better place".scan(/\b[a-z]/i).join.upcase
# => "WIABP"

\b matches word boundary. (between word character and non-word character). [a-z] match any alphabet.

\b[a-z] matches the first alphabet letter of word.

NOTE Above code will not work if there's a word(?) that starts with non-alphabet character. Also does not work if there's a word that contains a punctuation in it. (For example: World is 1 better-place.)

UPDATE

Using String#gsub with capturing group you will get the same result:

"world is a better place".gsub(/\s*(\S)\S*/, '\1').upcase
# => "WIABP"
like image 192
falsetru Avatar answered Dec 03 '25 15:12

falsetru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!