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