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

痞子三分冷 提交于 2019-12-01 09:04:55

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"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!