How can improve this sort method to meet the following conditions:
- exact matches returned first
- partial matches follow exact matches
def find_me
records = ["gogol", "garrison", "feathers", "grains"]
sorted = []
print "what are you looking for? "
term = gets.chomp.downcase
records.select do |record|
if term == record.downcase
#exact match
sorted << record
elsif term[0] == record[0] or term[1] == record[1] or term[2] == record[2]
#if the first three chars match add it
sorted << record
end
end
sorted.sort! {|b| term <=> b }
end
You could make a note of which ones are exact matches and which are full matches:
and then sort on both values and unpack the internal arrays:
I’m not sure what you’re expecting this sort to do:
but it is going to do strange things because the
sortblock is supposed to compare two elements of the array with each other and you’re completely ignoring the second one; for example, this happens for me:and the resultant ordering doesn’t make much sense.
The
each_with_objectis doing several things at once:matches;e.each_with_object(m)handsmto the block as its second argument and returnsm.This leaves you with a
matchesthat looks like this:with a leading 0 indicating an exact match and 1 indicating a prefix match. Then you can let
sortsortmatchesnormally sinceArray#<=>compares arrays element by element; 0 comes before 1 so the exact matches end up being first. Then we can throw away the exact/partial indicators usingmapto calllaston each of the inner arrays.