2
1

More than 3 years have passed since last update.

Rubyシルバー取得前 initializeメソッドまとめ

Last updated at Posted at 2019-12-08

 initializeメソッドをまとめてみました

  • initializeメソッドはnewをするごとに呼び出されるメソッド
  • 引数によりclassのデータを初期化する
book.rb
class Book               #クラスメソッドBookを定義
  def initialize(title)  #newするごとに呼び出されるインスタンスメソッド
    @title = title       #@nameはインスタンス変数
  end
  def review             #インスタンスメソッドreviewを定義
    "#{@title}は面白い"   #"#{}"で変数を展開
  end
end

 read = Book.new("Hoge")
 read.review

実行結果

Hogeは面白い

ただし
変数readの中身を変更することはできない。

book.rb
read.title =  "Fuga"
NoMethodError: undefined method `title=' for #<Book:0xxxxxxxxx @title="Hoge">

attar_accessorを定義すると、変数の中身を変更できるようになる

book.rb
class Book  
  attr_accessor :title             
  def initialize(title)  
    @title = title       
  end
  def review             
    "#{@title}は面白い"   
  end
end

 read = Book.new("Hoge")
 read.review
 read.title = "Fuga"
 read.review

実行結果

Hogeは面白い
Fugaは面白い

initializeメソッドを使わずに変数の中身を変更できるように書くには

book.rb
class Book
  def title=(title)
    @title = title
  end
  def review
    "#{@title}は面白い"
  end
end

reading = Book.new
reading.title = "HogeFuga"
reading.review

実行結果

HogeFugaはは面白い

ただし、newするさいに引数は持てない

book.rb
reading = Book.new("HOGEHUGA")
ArgumentError: wrong number of arguments (given 1, expected 0)
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