luodaoyi

Ruby8 继承(Inheritance)和模块(Modules)
继承示例# inheritance class User attr_accessor :name, :age...
右键或长按保存图片
17
2018/02

Ruby8 继承(Inheritance)和模块(Modules)

继承示例

# inheritance

class User
  attr_accessor :name, :age

  def initialize name, age
    @name, @age = name, age
  end

  def panels
    # ||= 操作符, 如果变量不存在 那么就赋值
    @panels ||= ['Profile', 'Products']
  end
end

class Admin < User

  def panels
    @panels ||= ['Profile', 'Products', 'Manage Users', 'System Setup']
  end

end

user = User.new('user_1', 18)
p user.panels

puts '-' * 30
admin = Admin.new('admin_1', 28)
puts admin.name
p admin.panels

# 查看这个类的父类
p Admin.superclass

常用關鍵字

super关键字
调用父类的同名方法
self關鍵字
指向當前作用域實例

# inheritance

class User
  attr_accessor :name, :age

  def initialize name, age
    @name, @age = name, age
  end

  def panels
    # ||= 操作符, 如果变量不存在 那么就赋值
    @panels ||= ['Profile', 'Products']
  end

  def to_s
    # self指向當前作用域實例
    "#{self.name} os #{self.age}"
  end

  # 定义方法的self代表类函数 (静态函数)
  def self.category
    'User'
  end

  # 一次性定义多个类方法
  class << self
    def category_2
      'User'
    end
  end
end


# < 符號代表繼承
class Admin < User

  def panels
    super #super 調用父類相同名稱的函數 (也可以帶參數)
    @panels.concat ['Manage Users', 'System Setup']
  end

end


user = User.new('user_1', 18)
p user.panels

puts '-' * 30
admin = Admin.new('admin_1', 28)
puts admin.name
p admin.panels


# 查看这个类的父类
p Admin.superclass

Modules 模块

作用

  1. namespace
  2. mixin: 实现类似于多类继承的功能
  3. storage

module关键字

  1. module: 声明一个module
  2. include: 把一个module的方法注入为实例放啊
  3. extend: 把一个module的方法注入为类方法
class User
  attr_accessor :name, :age

  def initialize name, age
    @name, @age = name, age
  end

  def panels
    @panels ||= ['Profule', 'Products']
  end

end


module Management
  def company_notifies
    'company_notifies'
  end
end

module CompanyFeature
  def new_record
    'new_record'
  end
end

class Admin < User
  include Management
  extend CompanyFeature

  def panels
    super
    @panels << ['Manage Users', 'System Setup']
  end
end

class Staff < User
  include Management
  extend CompanyFeature

  def panels
    super
    @panels << ['Tasks']
  end
end

p Admin.new_record
p Staff.new_record


puts '-' * 30
admin = Admin.new 'admin_1', 18
puts admin.company_notifies

puts '-' * 30
staff = Staff.new 'staff_1', 21
puts staff.company_notifies
Last modification:February 18th, 2018 at 03:13 am
If you think my article is useful to you, please feel free to appreciate

Leave a Comment