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

你可能感兴趣的:(Class,Ruby,Constructor)