Jwan622
Jwan622

Reputation: 11639

How do write two methods with different number of arguments in Ruby

I am trying to write this inside my class:

class << self
    def steps
      @steps.call
    end

    def transitions
      @transitions.call
    end

    def steps(&steps)
      @steps = steps
    end

    def transitions(&transitions)
      @transitions = transitions
    end
  end

That won't work since in Ruby, I can't do this kind of method overloading. Is there a way around this?

Upvotes: 0

Views: 646

Answers (2)

user886
user886

Reputation: 1197

Ruby does not support method overloading (see "Why doesn't ruby support method overloading?" for the reason). You can, however, do something like:

def run(args*)
  puts args
end

args will then be an array of the arguments passed in.

You can also pass in a hash of options to handle arguments, or you can pass in nil when you don't want to supply arguments and handle nil in your method body.

Upvotes: 0

coreyward
coreyward

Reputation: 80041

You can kind of do this with method aliasing and mixins, but the way you handle methods with different signatures in Ruby is with optional arguments:

def steps(&block)
  block.present? ? @steps = block : @steps.call 
end

This sort of delegation is a code smell, though. It usually means there's something awkward about the interface you've designed. In this case, something like this is probably better:

def steps
  @steps.call
end

def steps=(&block)
  @steps = block
end

This makes it clear to other objects in the system how to use this interface since it follows convention. It also allows for other cases, like passing a block into the steps method for some other use:

def steps(&block)
  @steps.call(&block)
end

Upvotes: 6

Related Questions