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.

attr_accessor(アクセサ)の使い方(Ruby初心者)

Posted at

#アクセサとは
定義:インスタンス変数にアクセスするために必要なもの。

前提:Rubyではそのままだとインスタンス変数にアクセスできない。
 →外部からの変数書き換え、呼び出しができない。

class User
    @name = ""
end
 
user = User.new
user.name = "taro"
p user.name
 
#=>rb:6:in `': undefined method `name=' for # (NoMethodError)
 

→インスタンス変数からの呼び出しを可能にするのがattr_reader(ゲッター)

class Human
  attr_reader :name #(ゲッター)
  def initialize(name)
    @name = name
  end
end
 
human = Human.new("taro")
puts human.name

実行結果

taro

→インスタンス変数を外部から書き換え可能にするのがattr_writer(セッター)

class Human
  attr_writer :name #(セッター)
  attr_reader :name
  def initialize(name)
    @name = name
  end
end
 
human = Human.new("taro")
puts human.name
human.name = "siro"
puts human.name

実行結果

taro
siro

→attr_reader(ゲッター)とattr_writer(セッター)の機能を足したのがattr_accessor(アクセサ)

class Human
  attr_accessor :name #アクセサ
  def initialize(name)
    @name = name
  end
end
 
human = Human.new("taro")
puts human.name
human.name = "siro"
puts human.name

実行結果

taro
siro

参照サイト
https://www.sejuku.net/blog/14168

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?