Thursday 2 June 2016

Ruby Modules and Modules vs Classes

Hi Readers,

Modules:

    require 'person_class' 
    module HasAge 
      attr_accessor :age 
    end 
    class Person 
      include HasAge 
    end 
    peter = Person.new("Peter"); peter.age = 33; puts peter.age 
    module MyApp 
      class Person 
        attr_accessor :hometown 
        def initialize(hometown) 
          self.hometown = hometown 
        end 
      end 
    end 
    peter = MyApp::Person.new("Stockholm"); puts peter.hometown 

Modules vs Classes:

  • Modules model characteristics or properties of entities or things. Modules can’t be instantiated. Module names tend to be adjectives (Comparable, Enumerable etc.). A class can mix in several modules.
  • Classes model entities or things. Class names tend to be nouns. A class can only have one super class (Enumeration, Item etc.).

Hope you understand.

Thanks

 


No comments:

Post a Comment

My Experience in RUBYCONF INDIA 2016

Hi Readers, Rubyconf India is a global event complementing other RubyConf events across the world. I attended this event held on 19-20 ma...