Kirill Zhuravlov Kirill Zhuravlov - 1 year ago 90
Ruby Question

Search an array by the first letters in Ruby?

I have an array

dictionary = [

How can I search first 5 matches or less(if there are no 5 matches) by first letters?

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


["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
just because it contains "a"

Answer Source

If I understood you correctly, you need first five words that starts with 'a'.

You can use String#start_with?: { |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: { |word| word.start_with?('a') }.first(5)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download