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!
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With