Free preview.You're sampling one lesson — enroll free to unlock all 8 lessons and track your progress.
Enroll free lesson
Classes and Instances
Classes and Instances
In this lesson — part of Objects and Classes — you'll learn classes and instances in Ruby and why it matters in real work.
Why it matters
Classes bundle data and behavior together — the core of object-oriented design.
Key ideas
- Classes and instances
- Fields and methods
- Constructors
- Encapsulation
In practice
Here's how it looks in idiomatic Ruby:
class Counter
attr_reader :count # generates a reader method
def initialize(start = 0)
@count = start # @count is an instance variable
end
def increment
@count += 1
end
end
c = Counter.new
c.increment
puts c.count # => 1
Ruby note: Instance state lives in @-prefixed variables, initialize is the constructor invoked by .new, and attr_reader/_accessor generate getter/setter methods.
Try it yourself
Exercise: In Ruby, write a Bank Account class with deposit and withdraw methods.
Recap
You now understand classes and instances and can apply it in Ruby. Mark this lesson complete and continue to the next one.
