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

点点圈 提交于 2019-12-19 09:23:43

问题


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!


回答1:


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"


来源:https://stackoverflow.com/questions/7329954/instance-variable-class-variable-and-the-difference-between-them-in-ruby

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