0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Ruby] アクセサメッソドについて

Posted at

アクセサメソッドとは

インスタンス変数を読み書きするメソッドのこと

 class User
  # 引数で受け取った値を@nameに代入するメッソド(セッター)
   def name=(name)
     @name = name
   end

  # インスタンス変数の内容を参照するメソッド(ゲッター)
   def name
     @name
  end
 end

> user = User.new
> user.name = "Alice"
=> "Alice"

attr_accessorメッソドを使えば、セッターやゲッターメッソドを定義する度にこのような機械的なコードを書かなくて済むようになる。

attr_accessor

 class User
    # @nameを読み書きするメッソドが自動的に定義される 
   attr_accessor :name
 end


> user = User.new
> user.name = "Alice"
=> "Alice"

また、複数の引数を渡すと、複数のインスタンスに対するアクセサメッソドを作成することができる。

 class User
   attr_accessor :name, :age, :address
 end


> user = User.new
> user.name = "Alice"
=> "Alice"
> user.age = 18
=> 18
>user.address = "東京"
=> "東京"
> user
=> #<User:0x00007ff18907ff30 @name="Alice", @age=18, @address="東京">

また、インスタンス変数の内容を読み取り専用にしたい場合はattr_reader、逆に書き込み専用にしたい場合はattr_writerを使う。

attr_reader

 class User
   attr_reader :name

    def initialize(name)
      @name = name
    end
  end


> user = User.new("Alice")
> user.name
=> "Alice"
# 読み取り専用なので、@nameを変更しようとするとエラーになる
> user.name = "Selka"
NoMethodError (undefined method `name=' for #<User:0x00007fdccb16b958 @name="Alice">)

attr_writer

 class User
   attr_writer :name

    def initialize(name)
      @name = name
    end
  end

> user = User.new("Alice")
> user.name = "Selka"
=> "Selka"
# 書き込み専用なので、@nameの参照はできない
user.name
NoMethodError (undefined method `name' for #<User:0x00007fe2ee8a8620 @name="Selka">)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?