App Academy

Can access variable made in while loop (Ruby)

Hi guys, first thing first, sorry for the broken english, I hope you understand what I’m trying to say. I’m kind of new in this platform, and when I was doing some exercises, I found out that you can access a variable that made inside the while loop (which is illegal in other programming languages) which I find kind of strange, but if I use array method like each etc, we can’t access the variable made inside the iteration which is good. Can someone explain this to me?

def test
  i = 0
  while i < 2
    someVar = "got me"
  end

  [1, 2, 3].each do |item|
    anotherVar = "can't touch this"
  end

  puts someVar     # got "got me"
  puts anotherVar # undefined local variable
end

test