Ruby基础知识之类

2019-09-25 09:43:57王冬梅

class Customer
    def initialize(name,age)
      @name,@age=name,age
    end
    class <<self
      def showName
        'ok'
      end
    end
end
 
puts Customer.showName

方法的访问性
public:公有的,默认情况下类中的方法是公有的,可以用在任何地方。构造方法initialize为私有的。
private:私有的,类内部使用的,只能被类或子类的实例方法所调用。只能通过self隐式调用,不能通过一个对象显示调用。一个私有方法m,只能通过m调用,而不能通过o.m或self.m调用。
protected:受保护的,类内部或子类内部使用的方法。与私有的区别是:除self隐式调用外,还可以通过该类对象显示调用。
可以通过以下方法来声明方法的访问性:

#访问性 private protected public
  private
  def private_method
    puts "private method testing"
  end
  protected
  def protected_method
    puts "protected method testing"
  end
  
  public:protected_method

工厂方法
使用new方法私有,然后通过类方法创建实例

class Fruit
  private_class_method:new
  def Fruit.CreateFruit
    new Fruit
  end
end
f=Fruit.CreateFruit

模块module

module作用之一是做为名字空间用。调用类时与调用常量相同:两个冒号
另一作用是作为混入。通过include把模块中的实例方法包含到其它类中。感觉功能像C#中的名字空间引入。