实例变量,类变量以及它们之间的区别(在ruby中) [英] instance variable, class variable and the difference between them in ruby
本文介绍了实例变量,类变量以及它们之间的区别(在ruby中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我很难理解实例变量,类变量以及它们在ruby中的区别...有人可以向我解释它们吗?我已经做了大量的Google搜索,只是无法完全理解它们.
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.
谢谢!
推荐答案
假设您定义了一个类.一个类可以有零个或多个实例.
Let's say you define a class. A class can have zero or more instances.
class Post
end
p1 = Post.new
p2 = Post.new
实例变量的作用域是特定实例.这意味着,如果您有实例变量title
,则每个帖子都会有自己的标题.
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"
这篇关于实例变量,类变量以及它们之间的区别(在ruby中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文