0

この並べ替え方法を改善して、次の条件を満たすにはどうすればよいですか。

  • 完全一致が最初に返される
  • 部分一致は完全一致の後に続く
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
4

2 に答える 2

2
def find_me
  records = ["gogol", "garrison", "feathers", "grains"]
  exact_matches   = []
  partial_matches = []  

  print "what are you looking for? "
  term = gets.chomp.downcase    

  records.each do |record|
    if term == record.downcase
      #exact match
      exact_matches << record
    elsif  term.slice(0, 3) == record.slice(0, 3)
      #if the first three chars match add it
      partial_matches << record
    end
  end

  # Just add the Arrays and it'll put the exact matches first and the 
  # partial ones last without a need for sorting. =)
  sorted = exact_matches + partial_matches 
end
于 2012-05-09T18:06:33.097 に答える
1

完全に一致するものと完全に一致するものをメモすることができます。

matches = records.each_with_object([]) do |record, m|
  if term == record.downcase
    m << [ 0, record ]
  elsif term[0, 3] == record[0, 3]
    m << [ 1, record ]
  end
end

次に、両方の値で並べ替えて、内部配列を解凍します。

matches.sort.map(&:last)

この種の機能を期待しているのかわかりません。

sorted.sort! {|b| term <=> b }

sortしかし、ブロックは配列の2つの要素を相互に比較することになっており、2番目の要素を完全に無視しているため、奇妙なことが起こります。たとえば、これは私のために起こります:

>> [4,2,1,2,4].sort { |x| 3 <=> x }
=> [4, 4, 1, 2, 2]

結果として得られる順序はあまり意味がありません。


each_with_object一度にいくつかのことをしています:

  1. 完全一致を見つけて、完全一致(先行0)としてマークします。
  2. プレフィックスの一致を見つけて、部分一致(先頭の1)としてマークします。
  3. 保存する結合リストを返しmatchesます; 2番目の引数としてブロックにe.each_with_object(m)渡して、を返します。mm

これにより、matches次のようなが表示されます。

[ [0, a], [1, b], [1, c], ... ]

先頭の0は完全一致を示し、1はプレフィックス一致を示します。次に、配列を要素ごとに比較するため、通常どおりにsort並べ替えることができます。0は1の前に来るので、完全一致が最初になります。次に、内部配列のそれぞれを呼び出すために使用して、正確/部分的なインジケーターを破棄できます。matchesArray#<=>maplast

于 2012-05-09T18:03:54.140 に答える