Variables inside/outside "while" loops (Same Char Collapse Problem)

Hi there.

Earlier in the Intro course, there was a point made about how variables that will be altered should be placed outside while loops or else they would be reset with every iteration. With that said, I’m wondering why the chars = str.split("") line goes inside the while loop for the correct answer to this problem, and why putting it outside returns undefined

Could you recall which video mentioned that? I believe it may have said that variables that will be altered need to go out of the loop (referring to Do loop iteration but not necessarily while loops). Either way, that problem was also a bit confusing for me to understand as well. Please let me know if you find the video so we could clarify.

chars = str.split("")
This line declares the variable (if it is not yet declared) and also initializes it (or reassigns it, if it already has been initialized) with whatever str.split("") evaluates to.

The reason you want it to be “re-assigned” inside the while loop is because you are changing the value of “str” with line 16. Every time your code reaches line 16, “str” is different. You need the line “char = str.split(”")" somewhere within the while loop, before you loop through it using .each (in line 8), otherwise, you are stuck with the same “chars”, every time you loop inside your while loop. if you are are changing “str” in line 16, but not reassigning “chars” with the updated “str”, you end up looping 8 to 17, over and over, with the same un-updated “chars”. You will never exist the loop!

This is easier to see if you indent 17 properly so it aligns with line 5. Line 5 to 17 is one block of code, and having 17 un-indented can cause confusion. Likewise, line 14 is ending the .each" block, NOT the if block, which can also cause confusion.

Line 9 to 14 is (an if) block within line 8 to 15 (which is the .each block), which is nested inside line 5 to 17 (the while block), which is nested inside line 1 to 20 (the same_char_collapse method block).

This is an alternate solution, which may be more readable to you.

def delete_duplicate(str)
  str.each_char.with_index do |char, i|
    if char == str[i + 1]
      return str[0...i] + str[((i + 2)..-1)]
  return str

def same_char_collapse(str)
  while str != delete_duplicate(str)
    str = delete_duplicate(str)
  return str