Accessing global variable from a function

V

Vitaly Belman

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.
 
S

Sebastian Steinlechner

--------------enig211ED926D3528FDDFC47BC1B
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 7bit

Vitaly said:
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

--------------enig211ED926D3528FDDFC47BC1B
Content-Type: application/pgp-signature; name="signature.asc"
Content-Description: OpenPGP digital signature
Content-Disposition: attachment; filename="signature.asc"

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)

iD8DBQFD2+iK8X9UC2T3lakRApbyAJ9FzNIQ4g0wHiGeHwG7DnLCtGL9yQCfUsGq
zTgoouW0ar8zHOt13LxUspU=
=Vl1C
-----END PGP SIGNATURE-----

--------------enig211ED926D3528FDDFC47BC1B--
 
J

JustAGuest

Vitaly said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top