无锡网站建设维护,制作公司网站应该考虑什么,小程序上线需要多少钱,wordpress 存储插件ruby 方法委托的优点在于#xff0c;可以将多个不同实例#xff08;或类#xff09;的方法组织在一起#xff0c;然后进行统一调用#xff0c;方便各类方法的统一管理。比如下边示例中的 color 和 username#xff0c;本来是不同类里边的方法#xff0c;但最后都可以统一…ruby 方法委托的优点在于可以将多个不同实例或类的方法组织在一起然后进行统一调用方便各类方法的统一管理。比如下边示例中的 color 和 username本来是不同类里边的方法但最后都可以统一使用 Man 的实例进行调用。
实例方法委托
require forwardableclass Personattr_accessor :name, :sex # attr_accessor相当于attr_reader和attr_writer的合集实际上是在定义类成员变量的时候就给他定义了一个get和set方法。def initialize(name, sex)name, sex name, sexenddef usernamenameend
endclass Colorattr_accessor :colordef initialize(color)color colorend
endclass Manextend Forwardabledef_delegators :person, :username, :sex # 将 username 和 sex 方法委托给 person在 Man 实例上调用 username 方法相当于调用 person 的 username 方法def_delegators :color, :color # 将 color 方法委托给 color在 Man 实例上调用 color 方法相当于调用 color 的 color 方法def initialize()person Person.new(Looking, male)color Color.new(white)end
endman Man.new
puts man.username # Looking
puts man.sex # male
puts man.color # white
类方法委托
require forwardableclass Persondef initialize()enddef self.nicknameself.name nicknameend
endclass Manextend SingleForwardabledef_delegators :Person, :nickname # 将 nickname 类方法委托给 Person在 Man 类中直接调用 nickname 类方法相当于调用 Person 的 nickname 方法def initialize()end
endputs Man.nickname # Person nickname