Syntax matters... class / module

November 6, 2006 by pedro mota

In Ruby, modules are collections of methods and constants. They cannot generate instances. Classes may generate instances (objects), and have per-instance state (instance variables).\n\nA class may inherit from another class, but not from a module.\nA module may not inherit from anything.\n\nModules may be mixed-in to classes and other modules. The mixed-in module’s constants and methods blend into that class, empower it.\n\nSubclasses require inheritance. A module may be included in a class to mimic multiple inheritance (the mixin facility)\n\nclass Compare\n  attr_accessor :a\n  def initialize a\n    @a = a\n  end\n\n  def > arg\n    puts \“Yep!\” if @a > arg\n  end\nend\n\ntest = Compare.new(3)\ntest > 1  # => Yep!\ntest.> 1  # => Yep!\ntest.>(1)  # => Yep!\nputs \“Yep, too!\” if 2 > 1  # => Yep, too!\nputs \“Yep ?\” if test < 1  # -> * \nputs \“Yep ?\” if 1 > test  # -> \n\n* undefined method `<’ for # (NoMethodError)\n comparison of Fixnum with Mixin failed (ArgumentError)\n\nJust as expected!

© 2018 | Follow on Twitter | pedro mg & Hugo