Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Accessing global variable from a function

1,035 views
Skip to first unread message

Vitaly Belman

unread,
Jan 28, 2006, 4:19:48 PM1/28/06
to
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.

--
Posted via http://www.ruby-forum.com/.


Sebastian Steinlechner

unread,
Jan 28, 2006, 4:56:42 PM1/28/06
to
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

--
It was mentioned on CNN that the new prime number discovered recently is
four times bigger than the previous record.
~ John Blasik

signature.asc

JustAGuest

unread,
Jan 28, 2006, 5:10:36 PM1/28/06
to
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

--
Posted via http://www.ruby-forum.com/.


0 new messages