免费注册 查看新帖 |

Chinaunix

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

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”.

论坛徽章:
46
15-16赛季CBA联赛之四川
日期:2018-03-27 11:59:132015年亚洲杯之沙特阿拉伯
日期:2015-04-11 17:31:45天蝎座
日期:2015-03-25 16:56:49双鱼座
日期:2015-03-25 16:56:30摩羯座
日期:2015-03-25 16:56:09巳蛇
日期:2015-03-25 16:55:30卯兔
日期:2015-03-25 16:54:29子鼠
日期:2015-03-25 16:53:59申猴
日期:2015-03-25 16:53:29寅虎
日期:2015-03-25 16:52:29羊年新春福章
日期:2015-03-25 16:51:212015亚冠之布里斯班狮吼
日期:2015-07-13 10:44:56
2 [报告]
发表于 2011-09-01 22:15 |只看该作者
还是村草发的质量高,瓜瓜发的简直是灌水

论坛徽章:
0
3 [报告]
发表于 2011-09-01 22:37 |只看该作者
回复 2# zhlong8


    嗯,你看到我那帖了?但很多人不会,还问我,所以我就发了。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP