如何在ruby中不使用循环的情况下在字符串中提取单词的首字母?

时间:2021-10-28 21:36:11

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

我尝试使用ruby获取字符串的首字母。以下是我写的。

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?

有没有更简洁的方法来产生同样的结果?

1 个解决方案

#1


6  

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]匹配任何字母表。

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

\b[a-z]匹配单词的第一个字母。

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:

使用带捕获组的字符串#gsub,您将得到相同的结果:

"world is a better place".gsub(/\s*(\S)\S*/, '\1').upcase
# => "WIABP"

#1


6  

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]匹配任何字母表。

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

\b[a-z]匹配单词的第一个字母。

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:

使用带捕获组的字符串#gsub,您将得到相同的结果:

"world is a better place".gsub(/\s*(\S)\S*/, '\1').upcase
# => "WIABP"