#7 Can someone explain why this works?


#1


https://www.codecademy.com/courses/ruby-beginner-en-MFiQ6/1/2?curriculum_id=5059f8619189a5000201fbcb

It's stated in the tutorial that "If you want to make a variable global from inside a method or class, just start it with a $, like so: $matz." However, in my code, I put the $ in front of the variable that wasn't in the class and it still worked. In fact, it wouldn't work without it. Is the instructions/tutorial wrong about this?

Edit I know that it says that "...you just define the variable
outside of any method or class, and voilĂ ! It's global...." However, wouldn't that mean that the code that I am to fix is correct already? Isn't it already being defined outside of the class?

class MyClass
  my_variable = "Hello!"
end

puts $my_variable


#2

I can't explain why it works because it doesn't. It may be permitted to pass the exercise, though. That is different.

If you examine your output, you will see it prints nil.

Consider,

class MyClass
  $my_variable = "Hello!"
end
puts $my_variable
my_variable = "Goodbye!"
puts my_variable
puts $my_variable
Hello!
Goodbye!
Hello!
nil

#3

So it's an error with the exercise then. Good to know.