6

I am having a hard time understanding instance variable, class variable and the difference between them in ruby... can someone explain them to me? I have done tons of Google searches, just can't understand them fully.

Thank you!

Dovak Qasht
  • 85
  • 2
  • 5

1 Answers1

10

Let's say you define a class. A class can have zero or more instances.

class Post
end

p1 = Post.new
p2 = Post.new

Instance variables are scoped within a specific instance. It means if you have an instance variable title, each post will have its own title.

class Post
  def initialize(title)
    @title = title
  end

  def title
    @title
  end
end

p1 = Post.new("First post")
p2 = Post.new("Second post")

p1.title
# => "First post"
p2.title
# => "Second post"

A class variable, instead, is shared across all instances of that class.

class Post
  @@blog = "The blog"

  def initialize(title)
    @title = title
  end

  def title
    @title
  end

  def blog
    @@blog
  end

  def blog=(value)
    @@blog = value
  end
end

p1 = Post.new("First post")
p2 = Post.new("Second post")

p1.title
# => "First post"
p2.title
# => "Second post"

p1.blog
# => "The blog"
p2.blog
# => "The blog"

p1.blog = "New blog"

p1.blog
# => "New blog"
p2.blog
# => "New blog"
Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
  • 2
    @maya: no, it does more. It allows you to type 'p1.blog = value' and call this method. In other languages it may be called 'a setter function'. – Arsen7 Sep 07 '11 at 07:58