简体   繁体   English

如何在Ruby中编写两个带有不同数量参数的方法

[英]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. 因为在Ruby中,我无法执行这种方法重载,所以这是行不通的。 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: 您可以使用方法别名和mixins来做到这一点,但是在Ruby中处理具有不同签名的方法的方式是使用可选参数:

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: 它还允许其他情况,例如将块传递到steps方法中以用于其他用途:

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

Ruby does not support method overloading (see " Why doesn't ruby support method overloading? " for the reason). Ruby不支持方法重载(原因请参见“ 为什么ruby不支持方法重载? ”)。 You can, however, do something like: 但是,您可以执行以下操作:

def run(args*)
  puts args
end

args will then be an array of the arguments passed in. args将是传入参数的数组。

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. 您还可以传递选项的哈希值来处理参数,或者当您不想在方法主体中提供参数并处理nil时可以传递nil

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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