【发布时间】:2021-05-02 14:16:52
【问题描述】:
我想创建一个函数,将一个字符串转换为一个相同的字符串数组,除了每个字符串中的下一个字母大写而其余的小写。我会给它一个字符串,并希望它在一个数组中返回该字符串,其中 是一个大写字母,如下所示:
wave("hello") => ["Hello", "hEllo", "heLlo", "helLo", "hellO"]
wave("two words") => ["Two words", "tWo words", "twO words", "two Words", "two wOrds", "two
woRds", "two worDs", "two wordS"]
我想出了这个,但它真的很大,而且需要很长时间才能运行。如何压缩它或编写一些新代码以使其运行得更好?
def wave(str)
ary = []
chars_array = str.chars
total_chars = chars_array.count
i = 0
until i == total_chars
if chars_array[i].match(/\w/i)
chars_array_temp = str.chars
chars_array_temp[i] = chars_array[i].upcase
fixed_string = chars_array_temp.join
ary << fixed_string
i = i+1
end
end
return ary
end
提前致谢!
【问题讨论】:
-
说到重复,看来您的问题与this recent one 相同。我特别喜欢得到绿色的答案。
标签: arrays ruby string methods capitalize