0

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.

3
  • 2
    if l.upcase means "if a character can be successfully converted to uppercase", this is not the same as "if a character is upper case". You're effectively trying to add a space in front of the first character that can be converted to uppercase, this shifts the character's position forward. With the next iteration of the loop you re-test the same character and add another space, and so on… Commented Apr 11, 2020 at 8:45
  • What is the error message? Commented Apr 11, 2020 at 8:47
  • 2
    @UrsaDK is right. Try replacing if l.upcase with if ('A'..'Z').include?(l). you should experience an infinite loop anyway though Commented Apr 11, 2020 at 8:53

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

7 Comments

If the string is large, then using a regex will also be much more efficient and I imagine faster (untested) then looping through all the characters of the string.
Alternate syntax: .gsub(/([A-Z])/, ' \1'), or even: .gsub(/[A-Z]/, ' \0')
And you may want to use [[:upper:]] to match non-ASCII uppercase characters, too.
Thanks a lot. Also thanks for explaining why the infinite loop happens
...or .gsub(/(?=[[:upper:]])/, ' '), which replaces a zero-width position before each capital letter with a space.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.