Search code examples
arraysrubystringmethodscapitalize

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)


I want to create a function that turns a string into a an array of strings that are the same, except each one capitalizes the next letter in the string while leaving the rest downcase. I will give it a string and want it to return that string in an array where the is one uppercase letter like this:

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

I came up with this, but it's really big and takes really long to run. How can I condense it or make some new code so it will run better?

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

Thanks in advance!


Solution

  • I would do this:

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