1

I've written code to take a string and return the same string back with all the letters changed to the next one and vowels uppercased. However, when I try to run it, the vowels don't seem to uppercase like I expect.

This is my code:

def LetterChanges(str)        
    str = str.downcase.split (" ")

    str.each do |word|
        i = 0
        while i < word.length
            word[i] = word[i].next
            word[i].upcase! if word[i] =~ /[aeiou]/
            i += 1
        end
    end

    return str.join(" ")
end

LetterChanges("helo world")

Can anyone tell me why my code isn't working?

Michael Gaskill
  • 7,913
  • 10
  • 38
  • 43

2 Answers2

1

When you access a part of a string via the [] method, you are returning a new string, rather than a pointer to that part part of the string.

You can see this by the following:

str = "abcdefgh"
str[5]              # "f"
str[5].upcase!      # "F"
str                 # "abcdefgh"

The upcase! method is working only on the new string, f, which is returned when you call str[5]. Because it is a new string, separate from the original string, the original string remains unchanged.

Instead you can use something like:

def LetterChanges(str)
  str.gsub(/[aeiou]/) {|letter| letter.next.upcase }
end
br3nt
  • 9,017
  • 3
  • 42
  • 63
  • Ah.... I understand now. So instead of gsub if I were to use `.each` it would still be the same string that gets modified – Shaurya Sinha May 30 '16 at 05:42
  • `gsub` is finding matches in the string based on the regex supplied to it. The value returned by the block is what the match is being replaced with. `gsub` is not modifying the original string but returning a new string with the matching bits replaced. – br3nt May 30 '16 at 05:45
0
def LetterChanges(str)
    str = str.downcase.split (" ")
    str.each do |word|
        i = 0
        while i < word.length       
            word[i] = word[i].next      
            word[i] = word[i].upcase! if word[i] =~ /[aeiou]/
            i += 1
        end
    end

    return str.join(" ")
end

LetterChanges("helo world")

will solve your proble...

dr. strange
  • 665
  • 7
  • 22