How can I capitalize a letter from a word one at a time, then add each instance of the word with a caps letter into a array?

Viewed 80

My code:

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

What it's supposed to do:

wave("hello") => ["Hello", "hEllo", "heLlo", "helLo", "hellO"]

I would really appreciate some help, as you probably know by looking at it I'm relatively new.

2 Answers
str = "hello"
str.size.times.map { |i| str[0,i] << str[i].upcase << str[i+1..] }
  #=> ["Hello", "hEllo", "heLlo", "helLo", "hellO"]

I would go about it as follows:

def wave(str)
  str = str.downcase # so we can ensure a wave even if the original string had capitalization
  str.each_char.with_index.map do |c,idx|
    str[0...idx].concat(c.upcase,str[idx.+(1)..-1])
  end
end
wave("hello")
#=> ["Hello", "hEllo", "heLlo", "helLo", "hellO"]
  • str.each_char.with_index.map do |c,idx| - This converts the String into an Enumerator and yields each character and its index to the map block.

  • str[0...idx] - In the block we slice the string into characters 0 through index (exclusive)

  • .concat(c.upcase,str[idx.+(1)..-1]) - Then we concatenate that with the current character upcased and the remaining portion of the String (index + 1 through the end of the String)

First 2 passes will look like:

  # idx = 0 
  # c = "h" 
  # str[0...idx].concat(c.upcase,str[idx.+(1)..-1])
  "".concat("H","ello")
  # idx = 1 
  # c = "e" 
  # str[0...idx].concat(c.upcase,str[idx.+(1)..-1])
  "h".concat("E","llo")
Related