How to Create Class in Ruby: Syntax and Examples
In Ruby, you create a class using the
class keyword followed by the class name and end. Inside the class, you can define methods and variables to describe its behavior and properties.Syntax
To create a class in Ruby, use the class keyword, then the class name starting with a capital letter, followed by end. Inside, you can add methods using def and variables.
- class ClassName: Starts the class definition.
- def method_name: Defines a method inside the class.
- end: Ends the method or class definition.
ruby
class ClassName
def method_name
# method code
end
endExample
This example shows how to create a simple Car class with a method to display its model.
ruby
class Car def initialize(model) @model = model end def display_model puts "Car model is #{@model}" end end my_car = Car.new("Toyota") my_car.display_model
Output
Car model is Toyota
Common Pitfalls
Common mistakes when creating classes in Ruby include:
- Not capitalizing the class name, which is required.
- Forgetting to use
endto close class or method definitions. - Not using
@for instance variables inside methods.
Here is an example of a wrong and right way:
ruby
# Wrong: class name not capitalized and missing @ for instance variable class car def initialize(model) @model = model end end # Right: class Car def initialize(model) @model = model end end
Quick Reference
Remember these key points when creating classes in Ruby:
- Class names must start with a capital letter.
- Use
defto define methods inside the class. - Instance variables start with
@. - Close all definitions with
end.
Key Takeaways
Use the
class keyword with a capitalized name to create a class.Define methods inside the class using
def and close with end.Instance variables must start with
@ to be accessible in methods.Always close class and method definitions with
end.Capitalization of class names is required in Ruby.