简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM