Rubyのアクセッサについての認識

attr_accessor

rubyにおけるインスタンス変数へのアクセッサということで、何となくインスタンス変数を明示的に定義しないといけないのかなと理解してた。

 class Hoge 

     attr_accessor :a, :b

     def initialize()

         @a, @b = 0, 1

     end

 end

C#的には、こんな感じかな

 class Hoge {

     private int a, b;

     public int A {

         get {return a;}

         set {a = value;}

     }

     public int B {

         get {return b;}

         set {b = value;}

     }

      public Hoge() { A = 0; B = 0; }

 }

 

だけど、当然、省略して、こういうのも有効なのね。

class Hoge 

    attr_accessor :a, :b

 def initialize()

        self.a = 0

        self.b = 1

    end

end

 

C#

 class Hoge {

     public int A { get; set; }

     public int B { get; set; }

     public Hoge { A = 0; B = 1; }

 }