Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 654
Tim Avatar asked Oct 14 '10 20:10

Tim


People also ask

How do you search an array?

Use filter if you want to find all items in an array that meet a specific condition. Use find if you want to check if that at least one item meets a specific condition. Use includes if you want to check if an array contains a particular value. Use indexOf if you want to find the index of a particular item in an array.

How do you check if an element is in an array in Ruby?

This is another way to do this: use the Array#index method. It returns the index of the first occurrence of the element in the array. This returns the index of the first word in the array that contains the letter 'o'. index still iterates over the array, it just returns the value of the element.


2 Answers

arr.grep(/^sa/) 
like image 139
Jörg W Mittag Avatar answered Oct 26 '22 03:10

Jörg W Mittag


>> arr.select {|s| s.include? 'sa'} => ["sandra", "sam", "sabrina"] 
like image 34
Nick Moore Avatar answered Oct 26 '22 03:10

Nick Moore