0

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?

1
  • Assign it if it's not nil, call it otherwise. Commented Apr 14, 2017 at 16:15

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.