Global Variables 17/20


#1

As per the notes given:
"Global variables can be declared in two ways. The first is one that's already familiar to you: you just define the variable outside of any method or class, and voilà! It's global. If you want to make a variable global from inside a method or class, just start it with a $, like so: $matz."

If I am trying to do the following to create a Global Variable by defining it outside the method it doesn't work

my_variable = ""

class MyClass
my_variable = "Hello!"
end

puts my_variable


#2

If you set my_variable to "Hello!" it will work. I think editor tests for this value to be printed.


#3

But if I try to do the following:
my_variable = "h"

class MyClass
puts my_variable
my_variable = "Hello!"
end

puts my_variable

i.e. try to access the global variable inside the class, I get error undefined local variable or method `my_variable' for Context::MyClass:Class.


#4

Other thing is that this should be acceptable to simply add '$' on the front of 'my_variable' inside the class.

class MyClass
$my_variable = "Hello!"
end

puts my_variable

But interpreter doesn't understand it as global variable then. Bug possible?

P.S. I needed to make it global outside the class, go to next exercise, go back to this one and then above method worked.


#5

Tried different things, and it seems you have to use the "$" regardless of the place you define it.

I think that what they mean by making it global by "defining the variable outside of any method or class", is that it's indeed global for the program, but except for methods and classes. If you want to make it global to every single part of the program, you have no other choice than using "$". At least that's what I think.


#6

@sial at this example here global variable "manufacturer" defined inside the class is printed using string interpolation like this;

puts "Manufacturer: #{$manufacturer}"

It seems like you need to use $ just before the variable name as @arjofocolovi has stated.


#7

@arjofocolovi and @negativefix

You are completely right :smile: I must have omitted it somehow. One of the next exercises showed me that if I define some variable with @, @@ or $ before the name I need to use them then calling that variables.

Many thanks for explanation :smile: