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?
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With