[英]How to search an array in Ruby?
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. 我将如何像在Rails中的活动记录对象一样搜索此数组。 For example, the query "sa" would return ['sandra', 'sam', 'sabrina']
. 例如,查询“sa”将返回['sandra', 'sam', 'sabrina']
。
Thanks! 谢谢!
arr.grep(/^sa/)
>> arr.select {|s| s.include? 'sa'}
=> ["sandra", "sam", "sabrina"]
A combination of select
method and regex would work select
方法和regex的组合可行
arr.select {|a| a.match(/^sa/)}
This one looks for prefixes, but it can be changed to substrings or anything else. 这个查找前缀,但可以更改为子字符串或其他任何内容。
a.select{|x|x[/^sa/]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.