Home  >  Q&A  >  body text

ruby - 方法可变参数(如*options)之后的参数,不可以设置默认值吗?

譬如:

def calculate(*numbers, method = {:add=>true})

就一直报错:

syntax error, unexpected '=', expecting ')' (SyntaxError)

检索The Ruby Programming Wikibook 的相关语法也没有提示,请问这是什么原因呢?

伊谢尔伦伊谢尔伦2710 days ago719

reply all(3)I'll reply

  • 黄舟

    黄舟2017-04-24 09:14:26

    Suppose you are the interpreter, what would you do with calculate({add: true}) 中的参数 {add: true} 分配给 *numbers 呢,还是 method?

    You can’t judge at all, right? So it's not allowed.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-24 09:14:26

    Can’t this kind of *numbers variable parameters only be at the end?

    def calc(method = {add: true}, *numbers); end is allowed, but the reverse is not allowed.

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-24 09:14:26

    Not allowed, there will be ambiguity

    reply
    0
  • Cancelreply