Accessing global variable from a function

Discussion in 'Ruby' started by Vitaly Belman, Jan 28, 2006.

  1. 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/.
    Vitaly Belman, Jan 28, 2006
    #1
    1. Advertising

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

    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

    --------------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--
    Sebastian Steinlechner, Jan 28, 2006
    #2
    1. Advertising

  3. Vitaly Belman

    JustAGuest Guest

    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/.
    JustAGuest, Jan 28, 2006
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Bryan Parkoff
    Replies:
    2
    Views:
    6,498
  2. Replies:
    1
    Views:
    383
    Michael Ekstrand
    Aug 21, 2005
  3. Mohanasundaram
    Replies:
    44
    Views:
    1,066
    Keith Thompson
    Aug 24, 2004
  4. sairam
    Replies:
    2
    Views:
    364
    Steve Holden
    Apr 5, 2007
  5. jubelbrus
    Replies:
    5
    Views:
    615
    JohnQ
    Jul 20, 2007
Loading...

Share This Page