gpt4 book ai didi

arrays - 将数组中的每个单词大写

转载 作者:行者123 更新时间:2023-12-01 21:21:23 26 4
gpt4 key购买 nike

我正在尝试将一个数组大写,其中一些字符串由多个单词组成,例如:

array = ["the dog", "the cat", "new york"]

我尝试使用:

array.map(&:capitalize)

但这只是将每个字符串的第一个字母大写。有什么建议么? (我对编码很陌生^_^)

我想要的输出是:

["The Dog", "The Cat", "New York"]

最佳答案

The documentation for String#capitalise说:

Returns a copy of str with the first character converted to uppercase and the remainder to lowercase.

那不是你想要做的。所以你需要写一些自定义的东西。

例如:

array.map { |string| string.gsub(/\b[a-z]/, &:upcase) }

我不清楚您是否/如何计划处理其他输入,例如全部大写、带连字符的单词或多行,...但是如果您的要求变得更详细,那么您可能需要扩展此实现.

关于arrays - 将数组中的每个单词大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63724888/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com