Forum: Ruby Accessing global variable from a function

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
0bf9907e642c62c7bcf3bb2f92d020d4?d=identicon&s=25 Vitaly Belman (vitalyb)
on 2006-01-28 22:19
I'd like to access a global variable from within a function, without
passing it as paramater. How do I do it? e.g

def func
    puts i
end

i = 5
func

In PHP, for example, I could use the "global" keyword in the function.
66f3a738dbb88ce201b5f42e19376351?d=identicon&s=25 Sebastian Steinlechner (Guest)
on 2006-01-28 22:57
(Received via mailing list)
Vitaly Belman wrote:
> I'd like to access a global variable from within a function, without
> passing it as paramater. How do I do it? e.g

You want to use a global variable, like so:

def func
  puts $i
end

$i = 5
func

The "$" tells Ruby it's global.

> In PHP, for example, I could use the "global" keyword in the function.

Yeah... one of the most distracting "features" of PHP *shrugs*.


Sebastian
A4671d40650effa73c7bf4eb6324d77e?d=identicon&s=25 JustAGuest (Guest)
on 2006-01-28 23:10
Vitaly Belman wrote:
> I'd like to access a global variable from within a function, without
> passing it as paramater. How do I do it?
Global variables start with a "$" so just write

def func
    puts $i
end

$i = 5
func
This topic is locked and can not be replied to.