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

谢谢!

4

3 回答 3

4

除非我误读了您的问题,否则您应该可以自己打电话super;例如:

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
于 2013-04-05T22:19:56.437 回答
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

如果要修改变量,则可以重新分配vararg 或使用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
于 2013-04-05T22:25:31.597 回答
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
于 2013-04-05T22:27:16.667 回答