繁体   English   中英

如何编写将关键字参数和哈希值结合在一起的ruby方法?

[英]How do I write a ruby method combining keyword arguments with hash?

我正在尝试设计一个像这样的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作为第二个参数

当前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}

暂无
暂无

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

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