Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

instance variable, class variable and the difference between them in ruby

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!

like image 209
Dovak Qasht Avatar asked Sep 07 '11 06:09

Dovak Qasht


1 Answers

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"
like image 130
Simone Carletti Avatar answered Sep 27 '22 23:09

Simone Carletti