method with same name and different parameters(Method Overloading) in Ruby

Ruby doesn't really support overloading.

This page gives more details and a workaround. Basically you create a single method with a variable number of parameters, and deal with them appropriately.

(I'd personally recommend writing one method to recognise the two different "faked overloads" and then one method for each overload, with different names reflecting the different parameters.)

Alternatively, just provide different names to start with :)


Just for comparison, here's how I would solve it:

#!/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