4
4

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.

Ruby初心者のためのattr_accessor

4
Last updated at Posted at 2016-03-16

問題

Rubyの attr_accessor とは何者なのか。

解決

インスタンス変数を定義しつつ、ゲッターとセッターも作ってくれる便利なやつ。

  • 別に使わなくてもいい (当然使ったほうがいいし普通は使う)
  • 怖がらなくてもいい (無害です)

解説

次のような「よくある動作」すなわち、あるクラスで、オブジェクトのインスタンス変数の読み書きがしたいとする。

user = User.new

# 値の書き込み
user.name = "Ichiro Tanaka"

# 値の読み出し
user.name
=> "Ichiro Tanaka"

そのクラス定義、これではダメ。(C言語あたりから来た人なら、いける気がしてしまうはず)

class user
  @user
end

値の「読み」「書き」のそれぞれに、メソッドを用意する必要がある。

class user

  #値の書き込み用メソッド
  def user=(val)
    @user = val
  end

  #値の読み出し用メソッド
  def user
    @user
  end

end

長い。こんなよくある動作のためにメソッド2つも人力で書くなんて…。
そこで登場するのがattr_accessor。

class User
  attr_accessor :name
end

こう書くだけで、読み書きに対応したインスタンス変数が用意される。
そんなインスタンス変数を複数個用意したいときも簡単。

class User
  attr_accessor :name, :email, :mobile, :birthday
end

コードが随分コンパクトになるので、積極的に使っていきましょう(自分へ)。

4
4
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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?