ruby中委托方法

2016-10-19 09:56:59来源:oschina作者:fxhover人点击



```
require 'forwardable'
class Person
attr_accessor :name, :sex
def initialize(name, sex)
@name, @sex = name, sex
end
end
class Man
extend Forwardable
def_delegators :@person, :name, :sex #将name和sex方法委托给@person,在Man实例上调用name方法相当于调用@person的name方法
def initialize(person)
@person = person
end
end
person = Person.new "fxhover", "man"
man = Man.new person
puts man.name #fxhover
puts man.sex #man
```

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台