Ruby Fundamentals: Classes & Objects
Master Ruby's Object-Oriented Programming Foundation for Rails Development
Ruby is the programming language, while Ruby on Rails is a framework built on Ruby. Understanding Ruby syntax is essential before diving deep into Rails development.
Core Ruby Concepts You'll Learn
Object-Oriented Fundamentals
Everything in Ruby is an object containing variables and methods. Learn how objects model real-world entities to make code more readable and powerful.
Methods and Classes
Define reusable blocks of code with methods and create blueprints for objects using classes. Master the building blocks of Ruby programming.
Interactive Ruby Practice
Use IRB to test Ruby concepts hands-on. Practice string concatenation, method calls, and object instantiation in real-time.
Learning Path Structure
Step Away from Rails
Temporarily focus on pure Ruby language fundamentals without web framework complexity
Learn Core Concepts
Master classes, methods, properties and object-oriented programming principles
Apply to Rails
Use Ruby foundation knowledge for deeper Rails development understanding
Object-oriented programming is simply meant to model the real-world
String Operations in Ruby
| Feature | Numbers | Strings |
|---|---|---|
| Addition Operation | 2 + 3 = 5 | "2" + "3" = "23" |
| Concatenation | Mathematical sum | Text joining |
| Return Value | Numeric result | Combined string |
Don't worry about typing indentation spaces - Terminal will automatically indent your code when you hit Return in Interactive Ruby.
Method Structure Components
def keyword
Stands for definition and indicates you're creating a new method. Always precedes the method name.
Method Name
The identifier used to call the method later. Use descriptive names like say_meow for clarity.
Method Body
The code that executes when the method is called. Contains the actual functionality you want to perform.
end keyword
Signifies that the method definition is complete. Required to close the method block properly.
When defining classes with methods in IRB, you must type 'end' twice - once for the method and once for the class. This is not a typo.
Class vs Instance Behavior
| Feature | Class Call | Instance Call |
|---|---|---|
| Syntax | Cat.say_meow | fluffy.say_meow |
| Result | Error message | "Meow!" |
| Reason | No actual cat exists | Specific cat instance created |
Object Instantiation Process
Define the Class
Create a template or blueprint that describes what objects of this type can do
Instantiate the Object
Use ClassName.new to create an actual instance from the class template
Call Instance Methods
Use dot syntax (object.method) to execute methods on the specific instance
When you create objects in Ruby, each gets a unique identifier like #<Cat:0x007f8ebaleef88>. This confirms that different instances are separate objects, even if they're from the same class.
Key Takeaways