More tools for lists
The big tools for lists you know already: map, select, sort_by, reduce. This lesson empties the rest of the toolbox – small methods that each save you a loop with a counter or a helper variable. The first one works like a zipper: zip lays two lists side by side and joins them, element by element, into pairs. to_h then makes a hash out of the pairs:
names = ["Chunky", "Kaz", "Isi"]
points = [42, 17, 35]
p names.zip(points)
names.zip(points).to_heach_with_index from lesson 8 counts the positions from 0 – that is why you wrote i + 1 there. each.with_index(1) starts counting wherever you like:
names.each.with_index(1) do |name, place|
puts "#{place}. #{name}"
endThe smallest and the largest at once? minmax. The two largest? max(2) – and min(2) gives the two smallest. And max_by(2) picks the two for which the block gives the most – here the two best pairs of name and score: a podium without sorting the whole list:
p points.minmax
p points.max(2)
names.zip(points).max_by(2) { |name, score| score }partition splits a list into two piles in one go: the elements for which the block says true, and the rest – select and reject at once. It returns the two piles as an array of two arrays, and passed, failed = … catches them in two variables at once. The test scores from lesson 13, with map, select and co.:
scores = [72, 45, 88, 91, 30, 60]
passed, failed = scores.partition { |s| s >= 60 }
p passed
failedeach_slice(n) cuts a list into pieces of n – the rows of a table, the pages of a long list, teams of four. The last piece gets whatever is left over:
("a".."z").each_slice(7) do |row|
puts row.join(" ")
endeach_cons(2) hands out pieces too, but they overlap: every element together with its neighbour – the first with the second, the second with the third, and so on. That is just what you need for changes from one day to the next. Without a block it passes the pairs on – to to_a, to look at them, or straight to map:
noon = [12, 15, 11, 18, 20] # degrees at noon, Monday to Friday
p noon.each_cons(2).to_a
noon.each_cons(2).map { |before, after| after - before }Sometimes the pieces have no fixed size, but you can tell where one ends. chunk_while keeps neighbours together as long as the block says true; slice_when cuts wherever the block says true – the same thing, seen from the other side. Chunky went to the lake on these days of the month. Which days were in a row?
lake = [1, 2, 3, 7, 8, 12]
runs = lake.chunk_while { |a, b| b == a + 1 }.to_a
p runs
p lake.slice_when { |a, b| b != a + 1 }.to_a
runs.map { |run| [run.first, run.last].uniq.join("-") }.join(", ")“1-3, 7-8, 12” – the way a calendar would put it; for a single day, uniq leaves just one number. The last tool: when the block of map returns an array for every element, you get a list of lists. flat_map makes one flat list out of it straight away – here every word of every sentence:
sentences = ["Chunky likes bacon", "Kaz likes eggs"]
p sentences.map { |s| s.split }
sentences.flat_map { |s| s.split }A rule of thumb: when you catch yourself writing a loop with a counter, a “previous element” or two helper arrays, look in the toolbox first. Two lists side by side: zip. Pieces: each_slice. Neighbours: each_cons. Runs: chunk_while. Two piles: partition.
days and steps: per_day – a hash from each day to its steps; changes – for every day from Tuesday on, how many steps more (or fewer) than the day before; and top_two – the two largest step counts.days = %w[Mon Tue Wed Thu Fri Sat Sun]
steps = [4200, 6100, 5800, 9000, 3500, 12000, 7400]
# per_day = ... # { "Mon" => 4200, "Tue" => 6100, ... }
# changes = ... # each day minus the day before: [1900, -300, ...]
# top_two = ... # the two largest step counts
"aaabcc" becomes "3a1b2c" – three a, one b, two c. Pack the sizzle of the bacon in the pan, sizzle, into packed; chunk_while finds the runs of equal letters. Then unpack secret into unpacked: every count there is a single digit, so each_slice(2) hands you count and letter in pairs.sizzle = "ssssizzzzle"
secret = "1c1h3u1n1k1y"
# packed = ... # "4s1i4z1l1e"
# unpacked = ... # the secret, unpacked