Reputation: 1461
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!
Upvotes: 46
Views: 55788
Reputation: 68006
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.
Upvotes: 14
Reputation: 15847
>> arr.select {|s| s.include? 'sa'}
=> ["sandra", "sam", "sabrina"]
Upvotes: 31