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?

initializeメソッド

Posted at

initializeメソッド

User.new

この時呼ばれるのがinitializeメソッドです。インスタンスを初期化するために実行したい処理があれば、このinitializeメソッドでその処理を実装します。(特に必要なければ定義しなくても構いません)。

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

失敗した

irb(main):055* class User6
irb(main):056*   attr_accessor :name, :age
irb(main):057*
irb(main):058> end
=> [:name, :name=, :age, :age=]
irb(main):059> user = User6.new("Alice", 30)
(irb):59:in `initialize': wrong number of arguments (given 2, expected 0) (ArgumentError)

  • この場合はinitializeメソッドが引数をインスタンス変数に代入していたため今までインスタンス変数の書き換えができていた。しかしそのinitializeメソッドなくなったためインスタンスの状態が無いためexpected 0になると考える

感想

railsはinitializeメソッドを使ったことがないので上位のクラスがうまくやって、簡単にできてるのか。

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?