如何在Ruby中搜索数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3937431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to search an array in Ruby?
提问by Tim
Say I have an array of strings
说我有一个字符串数组
arr = ['sandra', 'sam', 'sabrina', 'scott', 'mark', 'melvin']
How would I search this array just like I would an active record object in Rails. For example, the query "sa" would return ['sandra', 'sam', 'sabrina'].
我将如何搜索这个数组,就像我在 Rails 中搜索活动记录对象一样。例如,查询“sa”将返回['sandra', 'sam', 'sabrina'].
Thanks!
谢谢!
回答by J?rg W Mittag
arr.grep(/^sa/)
回答by Nick Moore
>> arr.select {|s| s.include? 'sa'}
=> ["sandra", "sam", "sabrina"]
回答by Nikita Rybak
A combination of selectmethod and regex would work
select方法和正则表达式的组合将起作用
arr.select {|a| a.match(/^sa/)}
This one looks for prefixes, but it can be changed to substrings or anything else.
这个查找前缀,但它可以更改为子字符串或其他任何内容。
回答by ghostdog74
a.select{|x|x[/^sa/]}

