Is it possible to do something like:
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
Thanks!
Is it possible to do something like:
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
Thanks!
Unless I'm misreading your question, you should be able to call super
by itself; 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")
produces
$ ruby test.rb
do something with heysome modification
You cannot use a method name with the super
call
If you use super
on it's own then it will call the super
class' implementation passing along the same arguments
class A
def a(var)
puts var
end
end
class B < A
def a(var)
super
end
end
B.new.a(1) #=> 1
If you want to modify the variable then you can either reassign the var
arg or use a super
call passing in arguments
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
or
class A
def a(var)
puts var
end
end
class B < A
def a(var)
super(2)
end
end
B.new.a(1) #=> 2
try the below:
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")
Output:
do something with 12
Another one:
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")
Output:
do something with 12