Ruby: Classes Flashcards
How do you define a ruby class?
class NameOfClass
end
A ruby class is written with a capital first letter and written in CamelCase.
How do you create a new instance of a class?
We can create new instances of this class using new:
NameOfClass.new
How do you mixin a module into a class?
You can include a module within a class definition. When this happens, all the module’s instance methods are suddenly available as methods in the class as well. They get mixed in. In fact, mixed-in modules effectively behave as superclasses. You must load or require the file before using include.
Example:
module Debug def who_am_i? "#{self.class.name} (\##{self.object_id}): #{self.to_s}" end end class Phonograph include Debug # ... end class EightTrack include Debug # ... end ph = Phonograph.new("West End Blues") et = EightTrack.new("Surrealistic Pillow")
ph. who_am_i? # => “Phonograph (#330450): West End Blues”
et. who_am_i? # => “EightTrack (#330420): Surrealistic Pillow”
By including the Debug module, both the Phonograph and EightTrack classes gain access to the who_am_i? instance method.