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 attr_accessorってなんぞぉ??

Posted at

#attr_accessorっなんすか?

rails チュートリアルのsessionあたり?トークン発行してのあたりで少し詰まったので

attr_accessorって何ぞってなったから調べたことをここに残しておこうと思う。

initialize クラスインスタンス生成 俗に言うnewされた際に1度だけ実行されるメソッド
Javaで言うコンストラクタと同じ意味っすね

sample.rb
 def initialize(name)
  
    # インスタンス変数@usernameに引数を代入
    @name = name
  end

##本題
ゲッターとセッターを同時に定義してくれるメソッドです。

test.rb
class User
  def initialize(name)
    @name = name
  end
end

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


# => 当然エラーですよねメソッド定義してないっすもいんね・・・・

#def name
#
#end

test2.rb
class User
  def initialize(name)
    @name = name
  end

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

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


user = User.new('Alice')

user.name # => Alice

##getter setter

getter,setterって言葉耳にしたことあるかもしれないですが
railsで書くとこんな感じです。
getter : attr_reader :name
setter : attr_writer :name

test3.rb
class User
  attr_reader :name # @name ゲッターメソッド
  attr_writer :name # @name セッターメソッド

  def initialize(name)
    @name = name
  end
end

user = User.new('Alice')

user.name # => Alice

実は更に短くなるんすよね・・・・

attr_accessor

test4.rb
class User
  attr_accessor :name

  def initialize(name)
    @name = name
  end
end

user = User.new('Alice')

user.name # => Alice

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?