I have an array:
dictionary = [
'abnormal',
'arm-wrestling',
'absolute',
'airplane',
'airport',
'amazing',
'apple',
'ball'
]
How can I search the first five matches, or less if there are not five matches, by their 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 I need it to return
["abnormal", "arm-wrestling", "absolute", "airplane", "airport"]
and do not return words like ["ball"] just because it contains "a".
If I understood you correctly, you need first five words that starts with 'a'.
You can use String#start_with?:
dictionary.select { |word| word.start_with?('a') }.first(5)
For better performance you can lazy select these five words. It will especially make sense if the collection you are performing search on is 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)
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