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!
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.
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.
arr.grep(/^sa/)
>> arr.select {|s| s.include? 'sa'} => ["sandra", "sam", "sabrina"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With