Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search an array by the first letters in Ruby?

Tags:

arrays

ruby

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".

like image 211
Kirill Zhuravlov Avatar asked Jun 28 '26 06:06

Kirill Zhuravlov


1 Answers

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)
like image 82
Andrey Deineko Avatar answered Jun 29 '26 23:06

Andrey Deineko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!