免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1938 | 回复: 0
打印 上一主题 下一主题

constructer of class in ruby [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-09-01 16:33 |显示全部楼层 |倒序浏览
constructer of class in ruby


.1. for a string class:



s = "foobar"  # this a literal constructor for strings using double quotes

s.class   => String



we see here that string respond to the method "class", and return the class it belong to.



2. instead of using literal constructor, we can use named constructor, so call the new method on the class name:



s = String.new("foobar")

s.class

s == "foobar"     =>    true



3. array works the same way:



a = Array.new([1,2,3])



4. hash is different:



h = Hash.new   => {}   # this will create a new empty hash

h[:foo]      => nil



but if you specify a value in the constructor call, this value will be the default value for the hash, so for each nonexistent key, it is value will be this value instead of nil.




h = Hash.new(0)

h[:foo]     =>   0



5. in the definition of the constuctor, the method name is



def initialize(param)

        .......

end



6. there is superclass method that will be useful:



s = String.new("foobar")

s.class   =>   String

s.class.superclass    =>  Object

s.class.superclass.superclass   =>  BasicObject

s.class.superclass.superclass.superclass   =>  nil



This pattern is true of every Ruby object: trace back the class hierarchy far enough and every class in Ruby ultimately inherits from BasicObject, which has no superclass itself. This is the technical meaning of “everything in Ruby is an object”.
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP