From 4d0969ccadb5e996138b0001c845b9ba01772cb7 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 21 Jul 2026 11:47:31 -0500 Subject: [PATCH] Add link to Ruby docs and apply markdown formatting --- ruby/use-slice-to-reorder-hash-keys.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/ruby/use-slice-to-reorder-hash-keys.md b/ruby/use-slice-to-reorder-hash-keys.md index ccf9827..d211304 100644 --- a/ruby/use-slice-to-reorder-hash-keys.md +++ b/ruby/use-slice-to-reorder-hash-keys.md @@ -4,7 +4,9 @@ I recently ran into some code that was building up a hash keyed by _category_. It was a series of chained method calls building and transforming to produce the hash. It then ended with `.slice(*CATEGORIES)`. -That `#slice` call at the end was doing two things: +That +[`Hash#slice`](https://docs.ruby-lang.org/en/master/Hash.html#method-i-slice) +call at the end was doing two things: 1. It was removing any key-value pairs not in `CATEGORIES` 2. It was reordering the hash keys based on the order they appeared in `CATEGORIES` @@ -23,12 +25,12 @@ Let's look at a minimum example of this: ``` - I first define `CATEGORIES` which is an (ordered) array of symbols that -represent the categories I care about. + represent the categories I care about. - Then I manufacture a hash of items by category. This is a bunch of dummy data, -including extra categories, meant to demonstrate what `#slice` can do. + including extra categories, meant to demonstrate what `#slice` can do. - Lastly I call `.slice(*CATEGORIES)` on this hash which both pairs it down to -that set of categories and reorders the hash so that the keys appears in the -same order they do in the `CATEGORIES` array. + that set of categories and reorders the hash so that the keys appears in the + same order they do in the `CATEGORIES` array. This might be useful if I've defined `CATEGORIES` to be in a specific display order and I'm preparing this hash for consumption in some UI layer.