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のゲッター・セッター・アクセサメソッドについてまとめてみた。

Last updated at Posted at 2021-03-14

前提

インスタンス変数はクラスの外から呼び出すことができない

.rb
class User
  def initialize(name)
    @name = name
  end
end
user = User.new('Alice')
puts @name

=> #クラスの外からインスタンス変数を呼び出した為出力されず

ゲッターメソッドとは

クラス内からインスタンス変数を参照するメソッド

セッターメソッドとは

クラス内からインスタンス変数を更新するメソッド

@nameをクラスの外から参照するためのメソッドを定義してみる(ゲッターメソッド)

.rb
class User
  def initialize (name)
    @name = name
  end
# ゲッターメソッド
  def name
    @name
  end
end

user = User.new('Alice')
puts user.name 

=> 'Alice'

@nameの内容をクラスの外から変更したい場合も変更用のメソッドを定義する(セッターメソッド)

.rb
class User
  def initialize(name)
    @name = name
  end
  # ゲッターメソッド
  def name
    @name
  end
  # セッターメソッド(rubyでは=で終わるメソッド名を定義すると変数に代入する形式でそのメソッドを呼び出す)
  def name=(value)
    @name = value
  end
end

user = User.new('Alice')

# ↓ここは変数に代入してる訳ではなく、name=というメソッド(セッター)を呼び出してる。また=の前にスペースがあっても使える
user.name = 'Bob'
puts user.name
=>'Bob'

アクセサメソッド

上記でやったセッターやゲッターを定義せずに省略することができる
メソッド名 内容
attr_reader: 変数名 参照を可能にする(ゲッター)
attr_writer: 変数名 更新を可能にする(セッター)
attr_accessor: 変数名 参照と更新両方可能にする(ゲッター・セッター)

attr_accessorメソッド

参照と更新両方可能にする(ゲッター・セッター)

.rb
class User
  attr_accessor :name

  def initialize (name)
    @name = name
  end
end

user = User.new('Alice')
# 変更
user.name = 'Bob'
# 参照
puts user.name 
=> 'Bob'

attr_readerメソッド

参照できるが変更はできない(ゲッター)

.rb

class User
  attr_reader :name

  def initialize (name)
    @name = name
  end

end

user = User.new('Alice')
# 参照は可能
puts user.name
=> 'Alice'

user.name = 'Bob'
=> 'undefined method `name=' for #<User:0x00007fca8b11eb28 @name="Alice"> (NoMethodError)
Did you mean?  name'

attr_writerメソッド

変更できるが参照できない(セッター)

.rb
class User
  attr_writer :name

  def initialize (name)
    @name = name
  end

end

user = User.new('Alice')
# 変更は可能
user.name = 'bob'
puts user.name 
=> undefined method `name' for #<User:0x00007fc7c48d87c0 @name="bob"> (NoMethodError)
Did you mean?  name=

まとめ

インスタンス変数はクラスの外から参照することができない
セッターゲッターがあることでクラスの外からインスタンス変数を参照したり更新することができる
アクセサメソッド使うとセッターとゲッターの定義を省略することができる

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?