Ruby 方法接受一个字符串和 returns 一个重复项数组,在每个重复项中大写字符串中的下一个字母(如波浪)

Ruby method that takes a string and returns an array of duplicates capitalizing the next letter in the string in each duplicate (like a wave)

我想创建一个函数,将一个字符串转换为一组相同的字符串,除了每个字符串将字符串中的下一个字母大写,而其余的小写。我会给它一个字符串,并希望它 return 数组中的那个字符串,其中是一个大写字母,如下所示:

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

提前致谢!

我会这样做:

def wave(word)
  words = Array.new(word.size) { word.dup }
  words.map.with_index { |e, i| e[i] = e[i].upcase; e } - [word]
end

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"]