中关村村草 发表于 2011-09-01 16:33

constructer of class in ruby

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()



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

zhlong8 发表于 2011-09-01 22:15

还是村草发的质量高,瓜瓜发的简直是灌水:em30:

2gua 发表于 2011-09-01 22:37

回复 2# zhlong8


    嗯,你看到我那帖了?但很多人不会,还问我,所以我就发了。
页: [1]
查看完整版本: constructer of class in ruby