Search an array by the first letters in Ruby? -


i have array:

dictionary = [    'abnormal',   'arm-wrestling',   'absolute',   'airplane',   'airport',   'amazing',   'apple',   'ball' ] 

how can search first 5 matches, or less if there not 5 matches, first letters?

input = "a" match = dictionary.select { |a| a.match(input) } puts match 

match returns

["abnormal", "arm-wrestling", "absolute", "airplane", "airport", "amazing", "apple", "ball"] 

but need return

["abnormal", "arm-wrestling", "absolute", "airplane", "airport"] 

and not return words ["ball"] because contains "a".

if understood correctly, need first 5 words starts 'a'.

you can use string#start_with?:

dictionary.select { |word| word.start_with?('a') }.first(5) 

for better performance can lazy select these 5 words. make sense if collection performing search on growing bigger:

dictionary.lazy.select { |word| word.start_with?('a') }.first(5) 

for case insensitive selection:

dictionary.lazy.select { |word| word.start_with?('a', 'a') }.first(5) 

Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -