2
1

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メソッドとその仲間たち

Posted at

attrメソッド

attr(name, writable = false)

第一引数nameにはインスタンス変数名
第二引数をtrueにすると書き込みも可能なメソッドを定義できる。

使い方例.rb
class Book
 attr :title

 def initialize(title)
  @title = title
 end
end

book = Book.new("たのしいRuby")
puts book.title
=>"たのしいRuby"

この時点で以下を入れても書き込めないのでエラーとなる
book.title = "経営学入門"

書き込みを定義した例.rb
class Book
 attr :title,true  #writable=falseのところをtrueにした!

 def initialize(title)
  @title = title
 end
end

book = Book.new("たのしいRuby")
puts book.title
=>"たのしいRuby"

# 書き込み可能にしたので以下は問題なく動く
book.title = "経営学入門"
puts book.title
=>"経営学入門"

じゃぁ複数のインスタンス変数を読み書き可能にするには??

attr :title, :price, true

とすれば可能か?
答えはどうやらNoである。

attr_accessorを使う

使い方例.rb
class Book
  attr_accessor :title, :price
  
  def initialize(title, price)
    @title = title; @price = price
  end
end
 
book = Book.new("たのしいRuby", 2310)
puts book.title
  =>"たのしいRuby"
book.price = 2000 #priceの書き換え
puts book.price
 => 2000  #2310が2000に書き換えられた!

ついでに
attr_readerはインスタンス変数の読み出し専用
attr_writerはインスタンス変数の書き込み専用をそれぞれ定義します。

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?