super定义:调用方法查找链中上一层级的方法

1.super()表示不带参数,不把参数带入到父类中。
2.super表示需要将参数带入到父类中,并且执行相应的方法。
3.使用super时,从继承体系中的上一层寻找和当前同名的方法,同样适用于module
4.报错之后,super之后的代码不执行
5.使用super时引发method_missing方法
6.super中如果存在参数值,参数值直接传递到父类方法中,和子类方法中的参数没有关系
7.如果super(x)形式,即是以参数形式,而非参数值形式,则super的参数数目必须和父类的参数数目相同
1.第一种:使用super()方法:
class Foo
  def show
    puts "Foo#show"
  end
end

class Bar < Foo
  def show(text)
    super()
    puts text
  end
end

Bar.new.show("test")
#下面是结果
Foo#show
test
#使用super()方法,不将参数带入到父类的show方法中,父类的show方法也不存在调用参数。
2.第二种:使用super方法:
class Foo
  def show
    puts "Foo#show"
  end
end

class Bar < Foo
  def show(text)
    super
    puts text
  end
end

Bar.new.show("test")
#wrong number of arguments (given 1, expected 0) (ArgumentError)

上面的代码中super方法会将text这个参数传递给父类的show方法,但是父类的方法其实没有参数选项,因此出错。

#代码修正
def show(text)
  puts "#{text}, Foo#show"
end
3.同样适用于module
module One
  def demo
    puts "this is the method one demo"
  end
end

module Two
  include One
  def demo
    super
    puts "this is the method two demo"
  end
end

class A
  include Two
end

obj = A.new
obj.demo
#结果
this is the method one demo
this is the method two demo
4.使用super报错之后不会执行super之后的语句
class Demo
  def method_missing(name, *args, &block)
    super
    puts "this is the method_missing"
  end
end

obj = Demo.new
obj.cc  #undefied method cc
#并且super之后的代码不执行
5.使用super时引发method_missing方法
class Father
  def laugh
    super
  end
end
Father.new.laugh #=>no superclass method `laugh' NoMethodError

#如果在继承体系中定义了method_missing方法,将丢失默认的提示信息
class Father
  def laugh
    super
  end

  def method_missing(method)
    puts "this is the missing method"
  end
end
Father.new.laugh #=> this is the missing method
6.super中如果存在参数值,参数值直接传递到父类方法中,和子类方法中的参数没有关系
class Foo
  def show(name)
    puts "Name: #{name}"
  end
end

class Bar < Foo
  def show
    super("jayzen") #直接传递参数值
  end
end

Bar.new.show #Name: jayzen
7.如果super(x)形式,即是以参数形式,而非参数值形式,则super的参数数目必须和父类的参数数目相同
class Foo
  def show(name)
    puts "Name: #{name}"
  end
end

class Bar < Foo
  def show(x)
    super(x)
    #super(x, y)会报错,参数数目必须相同
  end
end

Bar.new.show("jayzen") #Name: jayzen

results matching ""

    No results matching ""