Search code examples
rubystringcapitalization

Duplication in string capitalization. Ruby


I'm a Ruby newbie and I need your help with the below:

The task is to write a function that would return the following result:

   "Hello", "hEllo", "heLlo", "helLo", "hellO"

It also needs to work on "Two words"

The problem I have is with a letter 'L' as the function seems to be capitalizing both of them within a string.

Here is my code:

def wave(str)
  str.each do |word|
    count = -1

    word.length.times do
      count += 1
      puts word.gsub(word[count],word[count].capitalize)
    end
  end
end

wave("hello")

Solution

  • This should work:

    str = 'hi fi'
    p str.size.times.map{ str.dup }.map.with_index{ |s, i| s[i] = s[i].upcase; s unless s[i] == ' '}.compact
    #=> ["Hi fi", "hI fi", "hi Fi", "hi fI"]
    

    Here is how it works:

    First builds an array containing n times the word, where n is the word length:

    str.size.times.map{ str.dup } #=> ["hello", "hello", "hello", "hello", "hello"]
    

    Note that .dup is required in order to be able to modify each element of the array without affect all elements.

    Then, map with index (Enummerator#with_index) to upcase the letter at index. Finally returns s unless the current character is a space, in that case it returns nil, that's why .compact is called.

    That's the modified OP method, no need to pass an array of string as argument:

    def wave(str)
      str.length.times do |n|
        str_dup = str.dup
        str_dup[n] = str_dup[n].capitalize
        puts str_dup unless str_dup[n] == ' '
      end
    end
    
    wave('hi fi')
    #=> Hi fi
    #=> hI fi
    #=> hi Fi
    #=> hi fI