22

我有这个代码:

def setVelocity (x, y, yaw)
  setVelocity (Command2d.new(x,y,yaw))
end
def setVelocity (vel)
......
end 

vel 是一个具有 3 个属性的 Command2D 类,是 Comparable 并定义了 + ,基本上是一个方便我管理这 3 个属性的类,所以我想在我的库内部使用它(不想让它们私有,要么给它们奇怪的名字)。但是即使参数的数量不同,Ruby 似乎也只保留最后一个 setVelocity。所以当我用 3 个参数调用 setVelocity 时会说我只需要用一个参数调用该方法。

4

3 回答 3

40

Ruby 并不真正支持重载。

此页面提供了更多详细信息和解决方法。基本上,您创建一个具有可变数量参数的方法,并适当地处理它们。

(我个人建议编写一种方法来识别两种不同的“假重载”,然后为每个重载编写一种方法,不同的名称反映不同的参数。)

或者,只需提供不同的名称以开头:)

于 2009-07-10T09:31:40.753 回答
2

只是为了比较,这是我将如何解决它:

#!/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
于 2009-07-10T12:29:18.173 回答
0

使用attr_accessor添加属性,您将自动获取 getter 和 setter。或者使用attr_readerattr_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

在这种情况下,您可能会找到一个更好的名称,但我不知道您的xyyaw在您的上下文中的真正含义。

于 2009-07-10T09:59:05.440 回答