Kirill Zhuravlov Kirill Zhuravlov - 23 days ago 9
Ruby Question

Search an array by the first letters in Ruby?

I have an array

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


How can I search first 5 matches or less(if there are no 5 matches) by 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"

Answer

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 5 words - it will especially make sense with the collection you are performing search on is growing bigger:

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