简体   繁体   English

轨道匹配参数中字符串的结尾

[英]rails match ending of string in params

I am receiving params with keys like: 我收到带有以下参数的参数:

params["guest1_member1"]
params["guest2_member1"]
params["guest3_member2"]
params["guest4_member2"]

Is there some regex way to get params containing _member1 ? 是否有一些正则表达式方式来获取包含_member1参数?

Something like: 就像是:

params["*_member1"]

This should do it for you, without a regex: 这应该为您完成,而无需使用正则表达式:

params.select { |key, _value| key.ends_with?('_member') }

It's pretty self explanatory, selecting all elements from the params hash that end with '_member' . 这很'_member'说明,从params哈希中选择所有以'_member'结尾'_member'

You could also use the destructive: 您还可以使用破坏性的:

params.keep_if { |key, _value| key.ends_with?('_member') }`

Though note that will permanently remove all non matches from the params. 不过请注意,这将永久删除参数中的所有不匹配项。

Please note, this matches strings that end with your pattern, though you can switch to key.include?(...) if the pattern could appear anywhere in the key. 请注意,这可以匹配以您的模式结尾的字符串,尽管如果模式可以出现在键中的任何位置,您也可以切换到key.include?(...)

I've had a look and don't believe you can pass a regex to Hash::[] , though will be glad to be corrected if I'm wrong. 我看过了,不相信您可以将正则表达式传递给Hash::[] ,但是如果我错了会很高兴得到更正。

You could always use a regex within one of the above blocks, though I believe the options given are more readable. 尽管我相信给出的选项更具可读性,但您始终可以在上述块之一中使用正则表达式。

Hope that helps regardless - let me know how you get on. 希望对您有所帮助-让我知道您的生活。

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

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