0

I’m using Rails 4.2.7 on Ubuntu 14.04. According to this — Why doesn't ruby support method overloading? , I should be able to overload methods in my service class if each method has a different number of arguments. So I have created …

def create_my_object_time_obj(data_hash)
  create_my_object_time_obj(data_hash, nil)
end

def create_my_object_time_obj(data_hash, my_object_id)
  …

Yet, when I try and invoke the call that only takes a single argument

    my_object_time = service.create_my_object_time_obj(data_hash)

I get the error

Error during processing: wrong number of arguments (given 1, expected 2)
/Users/login/Documents/workspace/myproject/app/services/text_table_to_my_object_time_converter_service.rb:82:in `create_my_object_time_obj'

What’s the right way to overload my methods from my service class?

Community
  • 1
  • 1
Dave
  • 15,639
  • 133
  • 442
  • 830

2 Answers2

2

Ruby allows one and only one method for a given unique name, regardless of the method signature. The Ruby interpreter only looks at the names of methods, as opposed to the Java interpreter, which considers parameters as well as method names.

You can only override methods, with the latest version of a method of a given name taking precedence over all previous methods which share that name.

You can, however, get around the inability to overload by taking advantage of the splat (*) operator to pass a variable number of arguments to your method in an array, and then branching based on the number of passed parameters.

def foo(*args)
  if args.length == 1
    # logic for a single argument
  elsif args.length == 2
    # logic for two arguments
  else
    # logic for other conditions
  end
end
MarsAtomic
  • 10,436
  • 5
  • 35
  • 56
0

Just simple define your method as per below:

def create_my_object_time_obj(data_hash, my_object_id = nil)
  create_my_object_time_obj(data_hash, my_object_id)
end

now you can call this method by single argument:

 my_object_time = service.create_my_object_time_obj(data_hash)

this will work file. try this :)