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

Ruby・attr_accessorとは何か

Last updated at Posted at 2018-12-22

初見で意味がよくわからなかったので、メモ。

attr_accessorを設定することによって、そのオブジェクトのインスタンス変数を読み書きできるようになる(メソッドとして値を読み書きできる)。

class User
  # first_nameの読み書きを許可する
  attr_accessor :first_name

  def initialize(first_name, last_name, age)
    @first_name = first_name
    @last_name = last_name
    @age = age
  end

  # 省略
end

# "Ruby Alice"さん(20)を作る
user = User.new('Alice', 'Ruby', 20)
user.first_name 
=> "Alice"
user.first_name = 'ありす'
user.first_name
=> "ありす"

参考文献: プロを目指す人のためのRuby入門

0
0
1

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?