Eddie
Eddie

Reputation: 27

Insert a space in string

I am trying to .insert a space before the Uppercase letter if it's found. Here's what I came up with, but it seems like it's an infinite loop. I don't know why:

def solution(string)
  str = string.split("")
  str.each_with_index do |l, i|
   if l.upcase
    str.insert(l[i], " ")
   end
  end
  str.join("")
end

please let me know what I'm missing.

Upvotes: 0

Views: 461

Answers (1)

Ursus
Ursus

Reputation: 30056

Because it's often a bad idea changing the object you're looping on. You insert a space before the upcase letter you found, so the next iteration you found the upcase letter again and everything repeats.

In this case regular expression seems to fit nicely

def solution(string)
  string.gsub(/[[:upper:]]/, ' \0')
end

Upvotes: 3

Related Questions