Instance Methods
In this page:
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
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: