3
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 5 years have passed since last update.

attr_accessorの仕組みが分かった

Last updated at Posted at 2018-12-06

初めに

attr_accessorってrubyの勉強してたら結構出てきますよね。
最近になってやっとattr_accessorがどういった仕組みをしているかがわかりました。

attr_accessorの使い方

attr_accessorはこんな感じで使いますよね

attr_sample.rb
class User
  attr_accessor :age
end

user = User.new
user.age = 18
p user.age
=> 18

attr_accessorの仕組み

まずさっきのコードは

attr_sample2.rb
class User
  def age=(value)
    @age = value
  end

  def age
    @age 
  end 
end

user = User.new
user.age = 18
p user.age
=> 18

これと同じ

それでattr_accessor :ageの一行でどのように実装しているのかというと

attr_code.rb

class Object  

    def self.new_accessor(*args)
        args.each do |attr|
            define_method(attr) do
                instance_variable_get("@#{attr}")
            end 

            define_method("#{attr}=") do |value|
                instance_variable_set("@#{attr}", value)
            end
        end 
    end 
end 

class User 
    new_accessor :age, :name
end 

user = User.new 
user.age = 19
user.name = 'taro'
p user.age
p user.name
=> 19
=> 'taro'

みたいな感じです(多分…)

まずnew_accessorというクラスメソッドをObjectクラスをオープンして作っています。

そうすることによってObjectクラスが継承されているクラスすべてで使うことができます。

new_accessorの中身はdefine_methodでattrというメソッドとattr=というメソッドを作っています。

attrではinstance_variable_get で @attr の値を取得していて

attr=ではinstance_variable_set で @attr に値をセットしています

(attrは*argから得た値で今回の場合はageとnameです)

*argで不特定の個数の値をとることによって何個でもメソッドが作ることができます。

素晴らしい!!

なにか間違っていることがあるかもしれないのでその際はご指摘いただけたらと思います。

3
1
2

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
3
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?