如何一次大写一个单词中的一个字母,然后将单词的每个实例都用大写字母添加到数组中?
我的代码:
def wave(str)
ary = []
increase_num = 0
str = str.chars
until increase_num > str.size
ary << str[increase_num].upcase && increase_num += 1
end
end
它应该做什么:
wave("hello") => ["Hello", "hEllo", "heLlo", "helLo", "hellO"]
我真的很感激一些帮助,因为您可能通过查看它知道我是相对较新的。
回答
str = "hello"
str.size.times.map { |i| str[0,i] << str[i].upcase << str[i+1..] }
#=> ["Hello", "hEllo", "heLlo", "helLo", "hellO"]
- Or similarly (but with a possibly dubious use of `#tap`): `word = word.downcase; word.length.times.map { |i| word.dup.tap { |w| w[i] = w[i].upcase } }`.
- @muistooshort `Array.new(str.size) {str.downcase}.each_with_index {|s,idx| s[idx] = s[idx].upcase }`
- @CarySwoveland `Kernel#then` beautifies so many things e.g. `str.downcase.then {|str| str.size.times.map { |i| str[0,i] << str[i].upcase << str[i+1..] }}`
THE END
二维码