Class-level behavior lets you set rules or actions that apply to all objects made from that class. It helps keep things organized and avoids repeating the same code for each object.
Why class-level behavior matters in Ruby
class ClassName @@class_variable = value # class variable shared by all objects def self.class_method # code for class method end def instance_method # code for instance method end end
Class variables start with @@ and are shared by all instances of the class.
Class methods start with self. and can be called on the class itself, not on objects.
class Dog @@count = 0 def initialize @@count += 1 end def self.count @@count end end
class Car @@wheels = 4 def self.wheels @@wheels end end
This program creates two Book objects. It uses a class variable to count how many books were made. The class method total_books shows the count.
class Book @@total_books = 0 def initialize(title) @title = title @@total_books += 1 end def self.total_books @@total_books end def title @title end end book1 = Book.new("Ruby Basics") book2 = Book.new("Learn Programming") puts "First book title: #{book1.title}" puts "Second book title: #{book2.title}" puts "Total books created: #{Book.total_books}"
Class variables are shared across the class and all its instances, so changing it affects all objects.
Use class methods to perform actions related to the class itself, like counting objects or returning shared info.
Be careful with class variables in inheritance because subclasses share the same class variable.
Class-level behavior helps manage data and actions shared by all objects of a class.
Class variables and class methods are the main tools to create class-level behavior.
This keeps your code clean and avoids repeating the same information in every object.