In ruby how to use class level local variable? (a ruby newbie's question)

后端 未结 4 1052
挽巷
挽巷 2020-12-17 20:34

So suppose I have this (not working):

class User
   description = \"I am User class variable\"
   def print
       puts description
   end
end
4条回答
  •  爱一瞬间的悲伤
    2020-12-17 21:13

    In your case, the description is only local variable. You can change this scope using special characters @, @@, $:

    a = 5
    defined? a
    => "local-variable"
    
    @a = 5
    defined? @a
    => "instance-variable"
    
    @@a = 5
    defined? @@a
    => "class variable"
    
    $a = 5
    defined? $a
    => "global-variable"
    

    For your purpose, I think it might be using by this way

    class User
      def initialize(description)
        @description = description
      end
    
      def print
          puts @description
      end
    end
    
    obj = User.new("I am User")
    obj.print
    # => I am User
    

提交回复
热议问题