发布于 2016-01-25 09:16:23 | 128 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的Ruby教程,程序狗速度看过来!

Ruby编程语言

Ruby,一种为简单快捷的面向对象编程(面向对象程序设计)而创的脚本语言,在20世纪90年代由日本人松本行弘开发,遵守GPL协议和Ruby License。它的灵感与特性来自于 Perl、Smalltalk、Eiffel、Ada以及 Lisp 语言。


这篇文章主要介绍了Ruby中的public、private、protected区别小结,即Ruby中访问控制符的区别总结,需要的朋友可以参考下

重点关注private与protected

public

默认即为public,全局都可以访问,这个不解释

private

C++, “private” 意为 “private to this class”, 但是Ruby中意为 “private to this instance”.
意思是:C++中,对于类A,只要能访问类A,就能访问A的对象的private方法。
Ruby中,却不行:你只能在你本对象的实例中访问本对象的private方法。
因为Ruby的原则是“private意为你不能指定方法接收者”,接收者只能是self,且self必须省略!
所以Ruby中子类可以访问父类的private方法。但self.private_method是错的。

protected

可以在本类或子类中访问,不能在其它类中访问。

测试代码(public均可访问,代码略)


class A
 def test
  protected_mth
  private_mth
 
  self.protected_mth
  #self.private_mth   #wrong
 
  obj = B.new
  obj.protected_mth
  #obj.private_mth    #wrong
 end
 
 protected
 def protected_mth
  puts "#{self.class}-protected"
 end
 
 private
 def private_mth
  puts "#{self.class}-private"
 end
end
 
class B < A
 def test
  protected_mth
  private_mth
 
  self.protected_mth
  #self.private_mth   #wrong
 
  obj = B.new
  obj.protected_mth
  #obj.private_mth    #wrong
 end
end
 
class C
 def test
  a = A.new
  #a.protected_mth     #wrong
  #a.private_mth      #wrong
 end
end
 
A.new.test
B.new.test
C.new.test


注:ruby的访问控制不同于java,没有包的区别。
其它包中的类只要引用目标类,和目标类同包下类访问控制规则相同。



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务