Help us understand the problem. What is going on with this article?

[Ruby] アクセサメッソドについて

アクセサメソッドとは

インスタンス変数を読み書きするメソッドのこと

 class User
  # 引数で受け取った値を@nameに代入するメッソド(セッター)
   def name=(name)
     @name = name
   end

  # インスタンス変数の内容を参照するメソッド(ゲッター)
   def name
     @name
  end
 end

> user = User.new
> user.name = "Alice"
=> "Alice"

attr_accessorメッソドを使えば、セッターやゲッターメッソドを定義する度にこのような機械的なコードを書かなくて済むようになる。

attr_accessor

 class User
    # @nameを読み書きするメッソドが自動的に定義される 
   attr_accessor :name
 end


> user = User.new
> user.name = "Alice"
=> "Alice"

また、複数の引数を渡すと、複数のインスタンスに対するアクセサメッソドを作成することができる。

 class User
   attr_accessor :name, :age, :address
 end


> user = User.new
> user.name = "Alice"
=> "Alice"
> user.age = 18
=> 18
>user.address = "東京"
=> "東京"
> user
=> #<User:0x00007ff18907ff30 @name="Alice", @age=18, @address="東京">

また、インスタンス変数の内容を読み取り専用にしたい場合はattr_reader、逆に書き込み専用にしたい場合はattr_writerを使う。

attr_reader

 class User
   attr_reader :name

    def initialize(name)
      @name = name
    end
  end


> user = User.new("Alice")
> user.name
=> "Alice"
# 読み取り専用なので、@nameを変更しようとするとエラーになる
> user.name = "Selka"
NoMethodError (undefined method `name=' for #<User:0x00007fdccb16b958 @name="Alice">)

attr_writer

 class User
   attr_writer :name

    def initialize(name)
      @name = name
    end
  end

> user = User.new("Alice")
> user.name = "Selka"
=> "Selka"
# 書き込み専用なので、@nameの参照はできない
user.name
NoMethodError (undefined method `name' for #<User:0x00007fe2ee8a8620 @name="Selka">)
atsushs
プログラミング学習中です。 日々のアウトプットの場として記事を投稿しています。
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした