constructer of class in ruby_Ruby_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > Ruby > constructer of class in ruby

constructer of class in ruby

 2011/9/5 8:11:16  peryt  http://peryt.iteye.com  我要评论(0)
  • 摘要:1.forastringclass:s="foobar"#thisaliteralconstructorforstringsusingdoublequotess.class=>Stringweseeherethatstringrespondtothemethod"class",andreturntheclassitbelongto.2.insteadofusingliteralconstructor,wecanusenamedconstructor
  • 标签: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?monospace; vertical-align: baseline; color: #006400; padding: 0px; margin: 0px;">BasicObject, which has no superclass itself. This is the technical meaning of “everything in Ruby is an object”.

发表评论
用户名: 匿名