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

前端 未结 1 1645
没有蜡笔的小新
没有蜡笔的小新 2021-01-14 00:15

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

相关标签:
1条回答
  • 2021-01-14 00:30

    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"
    
    0 讨论(0)
提交回复
热议问题