前情提要:面试
在第五天的最后,咱们提到了一句话“相同的class的实体也没法使用别人的singleton method”。sql
在今天,咱们把焦点放在Ruby的method,继续了解存取限制:)网络
Ruby经典面试题目#06
说明Ruby的三种存取限制。3 levels of access control for Ruby methods.测试
让咱们用Ruby代码分别描述三种存取:Public,Protected,Private:this
class TingsIronmanProcess
def publish
p“Hi guys,this is my IT article for today!”
endspa
protected
def mydraft
p“Hi Mentor!Please read my draft.“
endsqlite
private
def myspace
p“I'm writing secretly here!”
end
end继承
day6 = TingsIronmanProcess.new
day6.publish # => Hi guys,this is my IT article for today!
以我本身生产第六天IT赛文章为例,为了防止网络断线,或是在IT邦写完误按其余的钮致使存盘出现问题,我一般在本机环境上编写天天的主题。在这段时间要搜集素材、测试代码,这个过程可能会有不少生产上的秘密、须要删除的错误等等之类的,过程艰辛不足为外人道矣,因此放在private的myspace方法孤芳自赏就好(jxpue)。开发
等到文章接近完成度高、可读性佳的地步,就放在protected的环境,开放一些权限给它人阅读,例如请Ruby前辈'馒头猫'先校稿,提供修改建议。get
因此若是在class外想要取得protected或private方法,都会出现NoMethodError错误:
day6.protected #=> undefined method `protected'(NoMethodError)
day6.private #=> undefined method `private'(NoMethodError)
当一切修改完毕,就能够品尝甜美果实,放到public区,给大众分享个人做品啦!
以上的类别写法能够改为:
class TingsIronmanProcess
def publish
p“Hi guys,this is my IT article for today!”
end
def mydraft
p“Hi Mentor!Please read my draft.“
end
def myspace
p“I'm writing secretly here!”
end
protected:mydraft
private:myspace
end
这种写法,我以为蛮相似于在开发Ruby on Rails项目上时常看到相似的构架,哪些套件只能在开发环境development使用,哪些在测试环境test、哪些在正式环境production使用的分组。
gem 'sqlite3',group::development
gem 'pg',group::production
若是我想把第六天的草稿send给menter看,能够把mydraft看成参数,使用send()方法,结果以下:
day6.send(:mydraft)#=>“Hi Mentor!Please read my draft.“
甚至把文章链接先send给某我的看,也行:(要当心!别把不能公开的东西乱放啊!)
day6.send(:myspace)#=>“Hi guys,this is my IT article for today!
若是馒头猫也想使用个人构架来撰写本身的铁人赛文章,能够继承个人类别:
class TingsIronmanProcess
protected
def mydraft
p“Hi Mentor!”
end
private
def myspace
p“I'm writing secretly here!”
end
end
class BaterProcess < TingsIronmanProcess
def bater_draft
mydraft
end
def bater_self_draft
self.mydraft
end
end
BaterProcess.new.bater_draft # Hi Mentor!
BaterProcess.new.bater_self_draft #Hi Mentor!
在加入继承后的新类别,咱们引入昨天self物件能够代替自身类别的观念。
以继承的类别来讲,在此呼叫Protected method的方式,不管是self.mydraft或是mydraft,输出结果都是Hi Mentor!。
但若是呼叫的是Private method myspace呢?
class BaterProcess < TingsIronmanProcess
def bater_space
myspace
end
def bater_self_space
self.myspace
end
end
若是咱们在这里使用.self,就会出错:
BaterProcess.new.bater_space # => I'm writing secretly here!
BaterProcess.new.bater_self_space # => private method `myspace'(NoMethodError)
龙哥的文章说到,呼叫private方法的时候,不能有明确的接收者。爱注意呀!
总结:在写铁人赛的文章时,我都尽量地把前几篇的概念拿到后面来使用,增长本身观念上的熟悉度,尽可能作到具备教育意义地环环相扣。(显示为八点档连续剧制做人?)
在今天Day6这篇文章里,咱们把次日继承和第四天self的概念拿来测试public、protect和private存取方法(xcsjbj),也发现了:
protected:mydraft
private:myspace
:mydraft,:myspace这些冒号在前面的参数。
这究竟是什么呢?
明天咱们就来讨论符号(Symbol)吧!:)