Instance Methods
An instance method is an action a particular object can perform, like a dog that can bark. It can use that object's own details.
In this page:
Syntax
class ClassName
def method_name(param)
# can use @instance_variables
end
end
object.method_name(argument)
Instance Methods
An instance method is defined inside a class with def and operates on a specific object's state, typically reading or modifying its instance variables.
Every object created from the class gets its own independent copy of those instance variables. Instance methods are called on an object with dot notation, like obj.method_name.
Note:
Instance variables (@var) are automatically nil until explicitly assigned -- there's no need to declare them ahead of time.
Example: Instance Methods
class Counter
def initialize
@count = 0
end
def increment
@count += 1
end
def value
@count
end
end
c = Counter.new
c.increment
c.increment
c.increment
puts c.value
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
- Forgetting
@incount += 1, which raisesNoMethodErrorbecausecountis a local variable. - Calling an instance method on the class, as in
Counter.increment, instead of on an object. - Expecting
incrementto return the new value only when the last expression is the assignment.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: