什么是正确的Ruby方法来简化和避免重复将相同的参数传递给每个继承类中的每个方法?
class Class0
# some attributes and methods here
end
class Class1 < Class0
def method1(arg1, arg2, arg3)
# do action #1 with arg1, arg2, arg3
end
def method2(arg1, arg2, arg3)
# do action #2 with arg1, arg2, arg3
end
end
class Class2 < Class0
def method3(arg1, arg2, arg3)
# do action #3 with arg1, arg2, arg3
end
def method4(arg1, arg2, arg3)
# do action #4 with arg1, arg2, arg3
end
end
obj1 = Class1.new
obj2 = Class2.new
obj1.method1(1, 2, 3)
obj1.method2(4, 5, 6)
obj2.method3(7, 8, 9)
obj2.method4(10, 11, 12)
如果你想简单地转发参数而不重复它们,你可以使用 splat 运算符*
:
class Class0
def method0(arg1, arg2, arg3)
# Say this method something with args such as this:
puts [arg1, arg2, arg3].join(", ")
end
end
class Class1 < Class0
def method0(*args)
super(*args)
end
end
实际上,只需从 Class1 调用super
即可转发参数,甚至不需要显式传递它们:
class Class1 < Class0
def method0(*args)
super
end
end
奇怪的是,super()
不会通过参数。如果向super
提供这些空括号或其他一些参数,这将覆盖默认行为(即转发所有参数(。
顺便说一下,splat 运算符不仅适用于super
- 您可以在定义方法参数或将参数传递给方法的任何地方使用它。还有一个"双 splat"运算符**
用于关键字参数。
https://alexcastano.com/everything-about-ruby-splats/