3

Possible Duplicate:
What does @@variable mean in Ruby?

What is the difference when I declare an object with double '@'

@@lexicon = Lexicon.new()

and declaring object with single '@' in Ruby?

@lexicon = Lexicon.new()
Community
  • 1
  • 1
Yasin
  • 287
  • 5
  • 15
  • 4
    I'm not understanding why this question is being downvoted. It's a perfectly legitimate question. – Ryan Bigg Nov 06 '12 at 10:01
  • Me neither :(. All people are not ruby genius like them who down voted it.If this site is not for learners then they should not let us register unless we have 10 years of programming experience – Yasin Nov 06 '12 at 10:12
  • @RyanBigg: If you hover over the downvote arrow you will get a tooltip which lists some of the possible legitimate reasons for downvoting. One of them is "This question does not show any research effort". Which this question doesn't: the question is answered in even the most basic beginner Ruby tutorial, and it can be answered trivially with a 3-second Google search, the first result of which is a duplicate on SO. The fact that the code snippets violate basic Ruby coding style further reinforces the appearance that the OP has not put *any* effort into answering the question himself. – Jörg W Mittag Nov 06 '12 at 12:12
  • @RyanBigg: Can you have a look at this problem: It's a ruby problem. http://stackoverflow.com/questions/13122615/errors-while-converting-python-script-to-ruby – Yasin Nov 06 '12 at 13:20
  • 2
    @JörgWMittag: Linking to a) the google result and b) the question that is returned with a *kind* message explaining that the question has been asked before is much nicer than anonymously downvoting. – Ryan Bigg Nov 06 '12 at 19:34

1 Answers1

7

The difference is that the first one is a class variable and the second one is an instance variable.

An instance variable is only available to that instance of an object. i.e.

class Yasin
  def foo=(value)
    @foo = value
  end

  def foo
    @foo
  end
end

yasin = Yasin.new
yasin.foo=1
yasin.foo #=> 1
yasin_2 = Yasin.new
yasin_2.foo #> nil

A class variable is available to all instances of the class (and subclasses, iirc) where the class variable was defined.

class Yasin
  def foo=(value)
    @@foo = value
  end

  def foo
    @@foo
  end
end

yasin = Yasin.new
yasin.foo=1
yasin.foo #=> 1
yasin_2 = Yasin.new
yasin_2.foo #=> 1
Ryan Bigg
  • 106,965
  • 23
  • 235
  • 261