【问题标题】:unable to spot syntax error in function signature无法在函数签名中发现语法错误
【发布时间】:2012-07-27 06:16:30
【问题描述】:

我有以下功能-

def add (*nums)
  nums.reduce(:+)
end

def subtract(first, *rest)
  first - rest.reduce(:+)
end

def calculate(*nums, options)
  first = nums.first
  rest = nums.reverse.drop(1)
  add(*nums) if options.size == 0
end     

以下是我在调用函数时收到的错误 -

语法错误,意外 '=',期待 ')' def calculate(*nums, 选项={}) ^

我的语法有什么错误?

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    你也可以有你的 splat 和你的选择,你只需要手动整理:

    def calculate(*nums)
      options = nums.last.is_a?(Hash) ? nums.pop : { }
      #...
    

    那么你可以毫无困难地说出calculate(1, 2, 3)calculate(1, 2, :size => 0)。当然,这假设 Hash 不是 nums 中某物的有效值。

    【讨论】:

    • 嗯,没想到 :)
    • 是的,我怎么没想到!谢谢
    【解决方案2】:

    splatted 参数后不能有默认参数。这给解析器造成了歧义。例如:

    calculate 1, 2, 3, 4
    

    4应该转到nums还是分配到options

    有几个选项可供选择

    移除选项的默认参数

    def calculate(*nums, options)
      # implementation
    end
    
    calculate 1, 2, 3, add: true # options
    calculate 1, 2, 3, {} # no options
    

    删除 splat

    def calculate(nums, options = {})
      # implementation
    end
    
    calculate [1, 2, 3], add: true # options
    calculate [1, 2, 3] # no options
    

    保持两者,但做更多的工作

    参见@muistooshort 的answer

    【讨论】:

    • 函数调用为calculate(1,2,3,4,:add true)
    • 然后删除选项的默认值,它应该可以解决问题。
    • 我还必须考虑没有为选项提供价值的可能性,在这种情况下会发生什么?
    • 然后你可以移除 splat 并显式传递一个数组。
    • 我正在尝试解决关于 ruby​​monk 的问题,这是此链接上的最后一个问题 - rubymonk.com/learning/books/1/chapters/19-ruby-methods/lessons/…。我还编辑了我的帖子以添加我的完整代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    • 2015-08-01
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多