Ruby中具有相同名称和不同参数的方法(方法重载)
我有以下代码:Ruby中具有相同名称和不同参数的方法(方法重载),ruby,overloading,Ruby,Overloading,我有以下代码: def setVelocity (x, y, yaw) setVelocity (Command2d.new(x,y,yaw)) end def setVelocity (vel) ...... end vel是一个Command2D类,有3个属性,是可比较的,定义+,基本上是一个方便我管理这3个属性的类,所以我想在我的库中内部使用它(不想让它们私有,也不想给它们起奇怪的名字)。 但是Ruby似乎只保留最后一个setVelocity,即使参数的数量不同。所以当我用3个参数
def setVelocity (x, y, yaw)
setVelocity (Command2d.new(x,y,yaw))
end
def setVelocity (vel)
......
end
vel是一个Command2D类,有3个属性,是可比较的,定义+,基本上是一个方便我管理这3个属性的类,所以我想在我的库中内部使用它(不想让它们私有,也不想给它们起奇怪的名字)。
但是Ruby似乎只保留最后一个setVelocity,即使参数的数量不同。所以当我用3个参数调用setVelocity时,我会说我只需要用一个参数调用该方法 Ruby并不真正支持重载 提供更多详细信息和解决方法。基本上,您可以创建一个参数数量可变的方法,并适当地处理它们 (我个人建议编写一个方法来识别两个不同的“伪造重载”,然后为每个重载编写一个方法,使用不同的名称来反映不同的参数。) 或者,只需提供不同的名称开始:)使用attr\u访问器添加属性,您将自动获得getter和setter。 或者使用attr\u reader或attr\u writer获取只读或只读属性
class Foo
attr_accessor :velocity
end
您现在可以按如下方式设置和获取此属性的值:
foo = Foo.new
foo.velocity = 100
puts foo.velocity # => 100
如果要添加基于某些参数设置属性的方法,请使用反映所需输入类型的名称:
def velocity_from_yaw(x, y, yaw)
velocity = Command2d.new(x, y, yaw)
end
在这种情况下,您可能会找到一个更好的名称,但我不知道您的x、y和偏航在您的上下文中到底是什么意思。为了进行比较,以下是我将如何解决它:
#!/usr/bin/env ruby
class Command2D
def initialize(x, y, yaw)
@command = [x, y, yaw]
end
end
class Vehicle
def velocity=(command_or_array)
case command_or_array
when Command2D
self.velocity_from_command = command_or_array
when Array
self.velocity_from_array = command_or_array
else
raise TypeError, 'Velocity can only be a Command2D or an Array of [x, y, yaw]'
end
end
private
def velocity_from_command=(command)
@velocity = command
end
def velocity_from_array=(ary)
raise TypeError, 'Velocity must be an Array of [x, y, yaw]' unless ary.length == 3
@velocity = Command2D.new(*ary)
end
end
v1 = Vehicle.new
v1.velocity = Command2D.new(1, 2, 3)
v2 = Vehicle.new
v2.velocity = [1, 2, 3]
p v1
p v2
诚然,没有一个话题你不在场。唤醒飞碟-你怎么没有“多面手”徽章?在撰写本文时,您已经发布了2140个不同的标签,前50个标签至少有30篇文章。让我想知道做一个“多面手”到底需要什么是的,多面手还没有实现-杰夫在Meta上暗示他不会直接做,但类似的事情。