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

Posted at

①エラーが起きるパターン

user.rb

class User
def initialize(name, age)
@name = name
@age = age
end
end

tanaka = User.new('田中太郎', 18)
tanaka.name

=> undefined method `name' for # (NoMethodError)

tanaka.age = 33

=> undefined method `age=' for # (NoMethodError)

②attr_accessorメソッド を使ったパターン

user.rb

class User

以下の記述でクラス外部から@name,@ageにアクセスが可能になる

attr_accessor :name, :age

def initialize(name, age)
@name = name
@age = age
end
end

tanaka = User.new('田中太郎', 18)
p tanaka.age #=> 18

tanaka.age = 33
p tanaka.age # => 33

このように、attr_accessorメソッドはインスタンス変数にアクセスするためのメソッドを裏側で定義してくれる。attr_accessorメソッドに指定されたインスタンス変数は、クラス外部から参照と変更の両方を行う事が出来るようになる。

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?