Ruby
Classes and Modules
Define classes with inheritance, mix in modules, and add class methods.
By EZ4Code Team
classmoduleoop
Code
# Module as namespace and mixin
module Loggable
def log(msg)
puts "[#{self.class}] #{msg}"
end
end
class Animal
include Loggable # instance methods
attr_accessor :name
def initialize(name)
@name = name
end
def speak
raise NotImplementedError
end
end
class Dog < Animal # inheritance
def speak
log "bark"
"Woof!"
end
end
class Cat < Animal
def speak
log "meow"
"Meow"
end
end
[Dog.new("Rex"), Cat.new("Tom")].each do |a|
puts "#{a.name}: #{a.speak}"
end
# Class methods and class variables
class Counter
@@total = 0
def self.count; @@total; end
def initialize; @@total += 1; end
end
3.times { Counter.new }
puts "Counters: #{Counter.count}"
# Open class to add a method
class String
def shout; upcase + "!"; end
end
puts "hello".shoutExplanation
Classes bundle state and behavior with single inheritance through <. Modules provide namespaces and reusable mixins via include, letting you compose capabilities without inheritance trees. attr_accessor generates getters and setters, and Ruby's open classes mean any class can be extended at runtime.
More Ruby Snippets
Blocks, Procs, Lambdas
Use blocks with yield, Procs, lambdas, and the & operator.
Iterators
Use each, map, select, reduce, group_by, and lazy enumerators.
Strings
Interpolate, trim, split, replace, and pattern-match strings.
Hashes
Build, default, transform, merge, and group with Hash.
Metaprogramming
Define methods dynamically, intercept with method_missing, and build DSLs.
Error Handling
Raise and rescue typed exceptions with ensure and retry.