简体   繁体   中英

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. For example, the query "sa" would return ['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

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/]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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