Difference between @instance_variable and attr_accessor

前端 未结 6 1828
日久生厌
日久生厌 2020-12-13 00:28

I Just started learning ruby and I don\'t see the difference between an @instace_variable and an attribute declared using attr_accessor.

Wh

6条回答
  •  鱼传尺愫
    2020-12-13 01:10

    And another answer more compact (for Java developers) attr_accessor :x creates the getters and setters to @x

    class MyClassA
      attr_accessor :x
    end
    

    is the same as

    class MyClassB
      def x=(value) #java's typical setX(..)
        @x=value
      end
      def x
        @x
      end
    end
    

提交回复
热议问题