Quick question about @ and @@

What’s the difference between @ and @@? Specifically, which should I use
if
I need a global variable in a non-OOP Ruby program?

Thanks!

Mike S.

Hi –

On Fri, 18 May 2007, Mike S. wrote:

What’s the difference between @ and @@? Specifically, which should I use if
I need a global variable in a non-OOP Ruby program?

@var is an instance variable (i.e., it represents the private state of
whatever object is in the role of ‘self’ at the point where @var
appears). @@var is a class variable, which is a kind of
de-encapsulated thing shared among a class, its descendants, and all
the instances of all those classes. There’s no connection or relation
between @var and @@var.

$var is a global variable.

David

quoth the Mike S.:

What’s the difference between @ and @@? Specifically, which should I use if
I need a global variable in a non-OOP Ruby program?

Thanks!

Mike S.

As I understand it, ‘@’ denotes an instance variable, visible only to
the
instance of a class, and ‘@@’ is a class variable, visible to all
instances
of the class.

If you need a plain old global try: $foovar

-d

Mike S. wrote:

What’s the difference between @ and @@? Specifically, which should I use
if
I need a global variable in a non-OOP Ruby program?

Thanks!

Mike S.

@ = Instance variable
@@ = Class variable

If you need a global variable in a non-OOP program, I guess I’d suggest
using a constant (capitalized variable). Here’s an example of @ and @@
usage:

irb(main):001:0> class Foo
irb(main):002:1> attr_accessor :a
irb(main):003:1> @@b = 0
irb(main):004:1> def initialize
irb(main):005:2> @a = 0
irb(main):006:2> end
irb(main):007:1> def add_a
irb(main):008:2> @a += 1
irb(main):009:2> end
irb(main):010:1> def add_b
irb(main):011:2> @@b += 1
irb(main):012:2> end
irb(main):013:1> def b
irb(main):014:2> @@b
irb(main):015:2> end
irb(main):016:1> end
=> nil
irb(main):017:0> one_foo = Foo.new
=> #<Foo:0x28dc078 @a=0>
irb(main):018:0> two_foo = Foo.new
=> #<Foo:0x28d9ea4 @a=0>
irb(main):019:0> one_foo.add_a
=> 1
irb(main):020:0> one_foo.a
=> 1
irb(main):021:0> two_foo.a
=> 0
irb(main):022:0> one_foo.add_b
=> 1
irb(main):023:0> one_foo.b
=> 1
irb(main):024:0> two_foo.b
=> 1

That clears things up a lot. I’ll use $var instead of @var for my
(usually
few!) global variables.

Thanks!

Mike S.

Hi,

Am Freitag, 18. Mai 2007, 01:20:26 +0900 schrieb Mike S.:

What’s the difference between @ and @@?

class C
@a, @@a = 3, 33

def set_a x, y ; @a, @@a = x, y ; end

def dump      ; puts "#@a, #@@a" ; end
def self.dump ; puts "#@a, #@@a" ; end

end

C.dump
puts

c = C.new
d = C.new

c.set_a 7, 77
d.set_a 8, 88

c.dump
d.dump
C.dump

The output is:

3, 33

7, 88
8, 88
3, 88

Bertram

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs