简体   繁体   English

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

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

I am trying to design an api that works like this: 我正在尝试设计一个像这样的api:

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

So I have this method in my client class: 所以我的client类中有此方法:

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

But I get syntax error, unexpected tIDENTIFIER 但是我收到syntax error, unexpected tIDENTIFIER

I also tried splatting: 我也尝试过喷溅:

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

But I get 但是我明白了

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

What's the right way to do this without switching around the order of the arguments. 在不切换参数顺序的情况下执行此操作的正确方法是什么。 The second argument has to be a hash and I don't want to use a keyword argument as a second parameter 第二个参数必须是哈希,并且我不想使用keyword argument作为第二个参数

The second works in current MRI and JRuby: 当前MRI和JRuby中的第二个作品:

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

The first one can't work because you can't both have keyword arguments and also automatically collect key-value pairs into a hash argument. 第一个无效,因为您既不能拥有关键字参数,也不能自动将键值对收集到哈希参数中。

EDIT in response to comment: 编辑以回应评论:

If you wanted to pass a hash and not collect extra keywords into a hash, then you need to reverse the signature: 如果您想传递一个散列而不希望将多余的关键字收集到散列中,则需要反转签名:

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

Or, you can splat your hash: 或者,您可以使用哈希值:

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

Or, you can make the second argument also into a keyword: 或者,您也可以将第二个参数设置为关键字:

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