`
peryt
  • 浏览: 55257 次
  • 来自: ...
最近访客 更多访客>>
社区版块
存档分类
最新评论
  • waiting: 既然都指定了dataType为'script'那就不必特别在b ...
    jQuery

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

1
2
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics