1
1

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 1 year has passed since last update.

【Ruby】初心者のためのattr_reader、attr_writer、attr_accessor

Last updated at Posted at 2023-10-23

はじめに

この記事ではattr_readerattr_writerattr_accessorを使用してインスタンス変数へのアクセス方法を説明し、コードを簡潔にする方法を紹介します。

attr_reader, attr_writer

Rubyのオブジェクト指向プログラミングでは、インスタンス変数へのアクセス方法が重要です。Rubyのオブジェクトメソッドは基本的に公開されていますが、データ(インスタンス変数)はプライベートです。つまり、インスタンス変数には直接アクセスできず、メソッドを通してのみアクセスできます。

例えば、次のRubyクラスを考えてみましょう:

class Person
  def initialize(name)
    @name = name
  end
end

person = Person.new("John")
puts person.@name # エラー!

インスタンス変数@nameに直接アクセスしようとすると、エラーが発生します。そのため、外部からインスタンス変数にアクセスできるようにするには、ゲッターメソッド(getter)とセッターメソッド(setter)を定義する必要があります。ゲッターメソッドはインスタンス変数の値を読み取るためのメソッドであり、セッターメソッドは新しい値を割り当てるためのメソッドです。

class Person
  def initialize(name)
    @name = name
  end

  # ゲッター(getter)メソッド
  def name
    @name
  end

  # セッター(setter)メソッド
  def name=(name)
    @name = name
  end
end

person = Person.new("John")
puts person.name # "John"
person.name = "Brian"
puts person.name # "Brian"

これで、nameインスタンス変数の値を読み取り、変更できるようになります。しかし、各インスタンス変数に対してこれらのメソッドを定義することは冗長になることがあります。これを簡略化するために、Rubyではattr_readerattr_writerが提供されています。

class Person
  # attr_readerを使用してnameのゲッターメソッドを生成
  attr_reader :name

  # attr_writerを使用してnameのセッターメソッドを生成
  attr_writer :name

  def initialize(name)
    @name = name
  end
end

person = Person.new("John")
puts person.name # "John"
person.name = "Brian"
puts person.name # "Brian"

これにより、attr_readernameのゲッターメソッドを生成し、attr_writernameのセッターメソッドを生成します。これらのメソッドを使用してインスタンス変数の値を読み取り、設定できます。

attr_accessor

attr_accessorメソッドはゲッターを生成するattr_readerメソッドとセッターを生成するattr_writerメソッドを1つのメソッドに結合したメソッドです。 このメソッドを使用する場合には、あえてattr_readerattr_writerをそれぞれ定義する必要はありません。attr_accessorを使用すると、コードがより簡潔になります。

class Person
  # attr_accessorを使用してnameのゲッターとセッターメソッドを生成
  attr_accessor :name

  def initialize(name)
    @name = name
  end
end

person = Person.new("John")
puts person.name # "John"
person.name = "Brian"
puts person.name # "Brian"

参考

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?