【问题标题】: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)Ruby 方法,它接受一个字符串并返回一个重复项数组,在每个重复项中将字符串中的下一个字母大写(如波浪)
【发布时间】: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

提前致谢!

【问题讨论】:

标签: arrays ruby string methods capitalize


【解决方案1】:

我会这样做:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-21
    • 2022-11-15
    • 2020-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多