Sorting and searching
Lists rarely arrive in the order you need: the high score table, the shopping list from A to Z, the cheapest offer first. Ruby sorts with sort – numbers by size, strings alphabetically – and reverse turns the result round:
p [5, 3, 9, 1].sort
p ["toast", "bacon", "egg"].sort
[5, 3, 9, 1].sort.reverseCareful with strings: Ruby compares them letter by letter by their character code, and every capital letter comes before every small one. So "Zebra" lands before "apple". sort_by sorts by whatever the block returns – here the word in lowercase:
words = ["bacon", "Zebra", "apple", "Chunky"]
p words.sort
words.sort_by { |w| w.downcase }sort_by is the everyday tool: words by their length, people by their age, anything by anything. Here are four foxes and how many strips of bacon each of them ate, sorted by age:
foxes = [
{ name: "Chunky", strips: 12, age: 3 },
{ name: "Kaz", strips: 7, age: 5 },
{ name: "Isi", strips: 12, age: 2 },
{ name: "Bo", strips: 3, age: 4 }
]
foxes.sort_by { |f| f[:age] }.map { |f| f[:name] }Who ate the most bacon? You don't need to sort the whole list for that – max_by and min_by name the winner straight away, and max_by(2) the top two:
p foxes.max_by { |f| f[:strips] }[:name]
p foxes.min_by { |f| f[:strips] }[:name]
foxes.max_by(2) { |f| f[:age] }.map { |f| f[:name] }Hm: Chunky and Isi both ate 12 strips, and max_by simply took the first. For a fair leaderboard the block returns an array. Ruby compares arrays element by element, so the second element only counts when the first ones are equal. Most strips first – the minus sign turns that order round – then by name:
board = foxes.sort_by { |f| [-f[:strips], f[:name]] }
board.each_with_index do |f, i|
puts "#{i + 1}. #{f[:name]} (#{f[:strips]})"
endBehind every comparison sits one small operator, the spaceship <=>. It answers -1 when the left side comes first, 0 when both are equal and 1 when the right one comes first. Give sort a block and you use it yourself – b <=> a instead of a <=> b sorts backwards:
p 3 <=> 7
p 7 <=> 7
p "egg" <=> "bacon"
[5, 3, 9, 1].sort { |a, b| b <=> a }And searching? include? asks whether something is there, index where it is, and find returns the first element the block agrees with. All three walk through the list from the front:
numbers = [4, 8, 15, 16, 23, 42]
p numbers.include?(15)
p numbers.index(23)
numbers.find { |n| n > 20 }In a long sorted list there is a much faster way – the one you use with a dictionary: open it in the middle, check whether your word comes before or after, forget the wrong half, repeat. That is bsearch, binary search. It finds the first element for which the block says true. Ten thousand numbers take about fourteen looks; a million would take twenty:
sorted = (3..30_000).step(3).to_a # 3, 6, 9 ... 30000
looks = 0
hit = sorted.bsearch { |n| looks += 1; n >= 20_000 }
puts "#{hit} after #{looks} looks"That is also why databases and search engines keep their data sorted. Lesson 13 (map, select & co.) showed the methods that sorting is made of; sort_by with an array as key is the trick you will use most.
scores holds the points of five foxes. Put their names into ranking: most points first, and with a tie in alphabetical order. Then name the fox with the fewest points in last_place – with min_by.scores = { "Chunky" => 42, "Kaz" => 17, "Isi" => 42, "Bo" => 8, "Mo" => 23 }
# ranking = ... # the names: most points first, a tie alphabetically
# last_place = ... # the name with the fewest points
menu into sorted_words: the shortest words first, and words of the same length alphabetically. Then find in the sorted list prices the first price of 10 or more – with bsearch, into first_big.menu = %w[bacon egg toast jam coffee tea]
prices = [1, 3, 4, 7, 12, 18, 25, 40]
# sorted_words = ... # shortest word first, words of the same length alphabetically
# first_big = ... # with bsearch: the first price that is 10 or more