是否可以执行以下操作:
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
谢谢!
答案 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