initialize
initialize is the setup that runs automatically when you make a new object, like assembling and charging a toy as it leaves the box. It gives the object its first values.
In this page:
Syntax
class ClassName
def initialize(param1, param2)
@attribute1 = param1
@attribute2 = param2
end
end
object = ClassName.new(value1, value2)
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Naming it
initorInitialize, when it must be exactlyinitialize. - Calling
Person.newwith the wrong number of arguments, which raisesArgumentError. - Forgetting the
@before instance variables, so the values are lost when the method ends.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: