instance variable, class variable and the difference between them in ruby
我很难理解Ruby中的实例变量、类变量以及它们之间的区别…有人能给我解释一下吗?我做了大量的谷歌搜索,只是不能完全理解它们。
谢谢您!
假设你定义了一个类。类可以有零个或多个实例。
1 2 3 4 5 | class Post end p1 = Post.new p2 = Post.new |
实例变量的作用域在特定实例中。这意味着如果您有一个实例变量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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" |
相反,类变量在该类的所有实例之间共享。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | 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" |