Collections

Most Ruby work happens in collections. Arrays, hashes and ranges introduce them; Enumerables and enumerators show the methods every collection shares. The toolbox lessons then go through the array and hash methods by task, nest collections inside each other, sort and compare, reach for sets, and end with lazy enumerators for streams that should not be built in memory.

4.1 Arrays Store ordered lists in Ruby arrays and reach elements by index. Open 4.2 Hashes Store labeled values in Ruby hashes and read them safely. Open 4.3 Ranges Describe intervals with Ruby ranges and use them in loops and checks. Open 4.4 Enumerables Transform collections with map, filter with select, fold with reduce, and search with find. Open 4.5 Enumerators Iterate lazily and build custom sequences with Enumerator. Open 4.6 The array toolbox Flatten and compact, union and difference, zip and product, push and shift: the array methods a script reaches for, and when each returns a new array. Open 4.7 The hash toolbox fetch with a block or a default, dig into nested data, merge and transform keys, and the mutable default that quietly changes every missing key. Open 4.8 Nested arrays and hashes Arrays of hashes, group_by with a block, sorting by one key, and turning rows into a report: the shape most JSON APIs return. Open 4.9 Enumerable by task The same list of jobs solved with map, select, partition, sum and each_with_object: a lookup table for the method that matches the task. Open 4.10 Sorting and comparison Compare with <=>, sort with sort and sort_by, keep a stable order, and make your own class sortable with Comparable. Open 4.11 Sets and set operations Set from the standard library: union, intersection, difference and subset tests, and the moment an array scan becomes a set lookup. Open 4.12 Lazy enumerators lazy turns a pipeline into one item at a time, which makes an infinite range usable and stops a big map from building a big array. Open

Lessons