Ruby - 有没有办法调用超类的方法,重载方法的名称相同

时间:2013-04-05 22:08:41

标签: ruby oop

是否可以执行以下操作:

class A
  def a(var)
    puts "do something with #{var}"
  end
end

class B < A
  def a(var)
    var = var + "some modification"
    #this is what I want to do:
    super.a(var)
  end
end

谢谢!

3 个答案:

答案 0 :(得分:4)

除非我误解你的问题,否则你应该可以自己致电super; e.g:

class A
  def a(var)
    puts "do something with #{var}"
  end
end

class B < A
  def a(var)
    var = var + "some modification"
    #this is what I want to do:
    #super.a(var)
    super
  end
end

v = B.new
v.a("hey")

产生

$ ruby test.rb
do something with heysome modification

答案 1 :(得分:2)

您不能将方法名称与super调用

一起使用

如果你自己使用super那么它将调用传递相同参数的super类'实现

class A
  def a(var)
    puts var
  end
end

class B < A
  def a(var)
    super
  end
end

B.new.a(1) #=> 1

如果要修改变量,则可以重新分配var arg或使用传递参数的super调用

class A
  def a(var)
    puts var
  end
end

class B < A
  def a(var)
    var = 2
    super
  end
end

B.new.a(1) #=> 2

class A
  def a(var)
    puts var
  end
end

class B < A
  def a(var)
    super(2)
  end
end

B.new.a(1) #=> 2

答案 2 :(得分:0)

尝试以下内容:

class A
  def a(var)
    puts "do something with #{var}"
  end
end

class B < A
  def a(var)
    var = var + "some modification"
    #this is what I want to do:
    #super.a(var)
    self.class.superclass.instance_method(:a).bind(self).call 12
  end
end

v = B.new
v.a("hello")

输出:

do something with 12

另一个:

class A
  def a(var)
    puts "do something with #{var}"
  end
end

class B < A
    alias :old_a :a
  def a(var)
    var = var + "some modification"
    #this is what I want to do:
    #super.a(var)
    old_a 12
  end
end

v = B.new
v.a("hello")

输出:

do something with 12