【问题标题】:How do I write a ruby method combining keyword arguments with hash?如何编写将关键字参数与哈希结合的 ruby​​ 方法?
【发布时间】:2017-05-07 15:14:30
【问题描述】:

我正在尝试设计一个像这样工作的 api:

client.entries(content_type: 'shirts', { some: 'query', other: 'more', limit: 5 })

所以我的client 类中有这个方法:

def entries(content_type:, query={})
  puts query
end

但我得到syntax error, unexpected tIDENTIFIER

我也尝试过喷溅:

def entries(content_type:, **query)
  puts query
end

但我明白了

syntax error, unexpected ')', expecting =>...ry', other: 'more', limit: 5 })

在不切换参数顺序的情况下执行此操作的正确方法是什么。第二个参数必须是一个哈希值,我不想使用keyword argument 作为第二个参数

【问题讨论】:

    标签: ruby methods hash keyword-argument


    【解决方案1】:

    第二个适用于当前的 MRI 和 JRuby:

    def entries(content_type:, **query)
      puts query
    end
    entries(content_type: 3, baz: 4)
    # => {:baz=>4}
    

    第一个不能工作,因为你不能既拥有关键字参数又自动将键值对收集到哈希参数中。

    编辑回应评论:

    如果你想传递一个哈希而不是将额外的关键字收集到一个哈希中,那么你需要反转签名:

    def entries(query={}, content_type:)
      puts query
    end
    entries(content_type: 3)
    # => {}
    entries({ baz: 4 }, content_type: 3)
    # => {:baz=>4}
    

    或者,你可以散布你的哈希:

    def entries(content_type:, **query)
      puts query
    end
    entries(content_type: 3, **{baz: 4})
    # => {:baz=>4}
    

    或者,您可以将第二个参数也变成关键字:

    def entries(content_type:, query: {})
      puts query
    end
    entries(content_type: 3)
    # => {}
    entries(content_type: 3, query: {baz: 4})
    # => {:baz=>4}
    

    【讨论】:

    • 是的,足够接近,但与我想要的 api 不完全匹配。我想让用户传入一个明确的哈希
    • 不——不能那样做。没有第一个参数,第二个是没有意义的
    • 在方法调用中散列散列 - 哇不知道!但这对于 api 用户来说要求太多了。我想我会重新设计电话
    猜你喜欢
    • 1970-01-01
    • 2011-02-01
    • 1970-01-01
    • 2012-11-19
    • 2018-03-01
    • 2014-03-28
    • 2013-05-10
    • 1970-01-01
    • 2011-01-28
    相关资源
    最近更新 更多