What is the difference between Methods and Attributes in Ruby?

后端 未结 5 508
抹茶落季
抹茶落季 2021-01-31 10:11

Can you give me an example?

5条回答
  •  礼貌的吻别
    2021-01-31 11:06

    class MyClass
      attr_accessor :point
    
      def circle
        return @circle
      end
    
      def circle=(c)
        @circle = c
      end
    end
    

    An attribute is a property of the object. In this case, I use the attr_accessor class method to define the :point property along with an implicit getter and setter methods for point.

    obj = MyClass.new
    obj.point = 3
    puts obj.point
    > 3
    

    The method 'circle' is an explicitly defined getter for the @circle instance variable. 'circle=' is an explicitly defined setter for the @circle instance variable.

提交回复
热议问题