Wednesday, November 6, 2013

Ruby: OOP (privacy)

Methods are public by default in Ruby.

class Test

  def public_m
  end

  private
  def private_m
  end

  // Again private method, because all methods after private keyword will be private
  def private_m_2
  end

end
Modules are containers for methods and constants.

module MyModule
  // Call it: MyModule::MOD_CONSTANT
  MOD_CONSTANT = "Module constat"

  // Call it: MyModule.my_method
  def my_method
  end
end
Require module by typing require 'MyModule', so it will be available in whole file (Module.my_method)

Include module to class, so it will be available inside class and all the methods can be called without module name:


class SimpleClass
  include MyModule // Without '
  def m
    my_method
  end
end
Infromation from: www.codeacademy.com

No comments:

Post a Comment