Tim
Tim

Reputation: 1461

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!

Upvotes: 46

Views: 55788

Answers (4)

ghostdog74
ghostdog74

Reputation: 342303

a.select{|x|x[/^sa/]}

Upvotes: 2

Jörg W Mittag
Jörg W Mittag

Reputation: 369428

arr.grep(/^sa/)

Upvotes: 67

Nikita Rybak
Nikita Rybak

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

Nick Moore
Nick Moore

Reputation: 15847

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

Upvotes: 31

Related Questions