initialize
In this page:
initialize
initialize is a special method that runs automatically whenever .new is called on a class, used to set up an object's initial state. Its parameters become the arguments you pass to .new. Unlike most methods, initialize is called implicitly and its return value is ignored -- .new always returns the new object itself.
Note: initialize's return value is always ignored -- .new always returns the newly created object, no matter what initialize returns.
Example: initialize
class Person
def initialize(name, age)
@name = name
@age = age
end
def introduce
puts "I'm #{@name}, #{@age} years old"
end
end
alice = Person.new("Alice", 30)
alice.introduce
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: