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?

アクセサメソッド

Last updated at Posted at 2024-11-12

アクセサメソッドとは

インスタンス変数の値を読み書きするメソッドのことをアクセサメソッドと呼びます(他の言語では「ゲッターメソッド」や「セッターメソッド」と呼ぶこともあります)。Rubyの場合、単純にインスタンス変数の内容を外部から読み書きするのであれば、attr_accessorというメソッドを使って退屈なメソッド定義を省略できます。

読み書き両方できるattr_accessor

irb(main):001* class User
irb(main):002*   attr_accessor :name
irb(main):003*
irb(main):004*   def initialize(name)
irb(main):005*     @name = name
irb(main):006*   end
irb(main):007> end
=> :initialize
irb(main):008> user = User.new("Alice")
=> #<User:0x000000010c1a6870 @name="Alice">
irb(main):009> user.name
=> "Alice"
irb(main):010> user.name = "Bob"
=> "Bob"
irb(main):011> user.name
=> "Bob"

読み専用 attr_reader

irb(main):012* class User2
irb(main):013*   attr_reader :name
irb(main):014*
irb(main):015*   def initialize(name)
irb(main):016*     @name = name
irb(main):017*   end
irb(main):018> end
=> :initialize
irb(main):019> user = User2.new("Alice")
=> #<User2:0x000000010fa7ff98 @name="Alice">
irb(main):020> user.name
=> "Alice"
irb(main):021> user.name="Bob"
(irb):21:in `<main>': undefined method `name=' for #<User2:0x000000010fa7ff98 @name="Alice"> (NoMethodError)

user.name="Bob"
    ^^^^^^
Did you mean?  name

書き込み専用 attr_writer

irb(main):022* class User3
irb(main):023*   attr_writer :name
irb(main):024*
irb(main):025*   def initialize(name)
irb(main):026*     @name = name
irb(main):027*   end
irb(main):028> end
=> :initialize
irb(main):029> user = User3.new("Alice")
=> #<User3:0x000000010c16e600 @name="Alice">
irb(main):030> user.name
(irb):30:in `<main>': undefined method `name' for #<User3:0x000000010c16e600 @name="Alice"> (NoMethodError)

user.name
    ^^^^^
Did you mean?  name=
...
irb(main):031> user.name="Bob"
=> "Bob"

複数指定も可

irb(main):042* class User5
irb(main):043*   attr_accessor :name, :age
irb(main):044*
irb(main):045*   def initialize(name,age)
irb(main):046*     @name = name
irb(main):047*     @age = age
irb(main):048*   end
irb(main):049> end
=> :initialize
irb(main):050> user = User5.new("Alice", 30)
=> #<User5:0x000000010c12f4a0 @age=30, @name="Alice">
irb(main):051> user.name
=> "Alice"
irb(main):052> user.age
=> 30
irb(main):053> user.age = 40
=> 40
irb(main):054> user.age
=> 40

感想

こういうメソッドがあるからrailsも簡単に操作できるようになってるんだな

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?