views:

75

answers:

4

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!

+2  A: 
>> arr.select {|s| s.include? 'sa'}
=> ["sandra", "sam", "sabrina"]
invariant
+2  A: 

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.

Nikita Rybak
+9  A: 
arr.grep(/^sa/)
Jörg W Mittag
+ 1 for the what I believe is the lightest sql hit as it performs only one function.
Trip
works perfectly, thanks!
Tim
A: 
a.select{|x|x[/^sa/]}
ghostdog74