To create a truly global variable, use $
:
def fun1
$foo = 'bar'
end
def fun2
puts $foo
end
Here $foo
is available outside the class instance once fun1
has been called.
As noted in the first comment, this should be used sparingly:
They are dangerous because
they can be written to from anywhere. Overuse of globals can make
isolating bugs difficult; it also tends to indicate that the design of
a program has not been carefully thought out.
What you're probably asking for is an instance variable, which uses @
:
def fun1
@foo = 'bar'
end
def fun2
puts @foo
end
Here @foo
is available anywhere in the current instance of the class, again once it has been declared by calling fun1
.
See for example this on the various variable scopes in ruby.