是否可以执行以下操作:
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
谢谢!
除非我误读了您的问题,否则您应该可以自己打电话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
您不能在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
试试下面的:
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