From 329ce1aa3e20bf42eea24e82d49bd22cf28f3825 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Fri, 20 Mar 2026 09:18:10 -0500 Subject: [PATCH] Add Filter By Type as a Ruby TIL --- README.md | 3 ++- ruby/filter-by-type.md | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 ruby/filter-by-type.md diff --git a/README.md b/README.md index 2715af4..4f15b6a 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ working across different projects via [VisualMode](https://www.visualmode.dev/). For a steady stream of TILs, [sign up for my newsletter](https://visualmode.kit.com/newsletter). -_1760 TILs and counting..._ +_1761 TILs and counting..._ See some of the other learning resources I work on: @@ -1428,6 +1428,7 @@ If you've learned something here, support my efforts writing daily TILs by - [FactoryGirl Sequences](ruby/factory-girl-sequences.md) - [Fail](ruby/fail.md) - [Fetch Warns About Superseding Block Argument](ruby/fetch-warns-about-superseding-block-argument.md) +- [Filter By Type](ruby/filter-by-type.md) - [Find The Min And Max With A Single Call](ruby/find-the-min-and-max-with-a-single-call.md) - [Finding The Source of Ruby Methods](ruby/finding-the-source-of-ruby-methods.md) - [Format A Hash Into A String Template](ruby/format-a-hash-into-a-string-template.md) diff --git a/ruby/filter-by-type.md b/ruby/filter-by-type.md new file mode 100644 index 0000000..578533d --- /dev/null +++ b/ruby/filter-by-type.md @@ -0,0 +1,37 @@ +# Filter By Type + +In Ruby, we have several ways to check if something is a certain type (class or +subclass). A couple common approaches you might see are `#is_a?` and `===` +(case equality operator): + +```ruby +> 3.is_a?(Integer) +=> true +> Integer === 3 +=> true +> 3 === Integer +=> false +``` + +Notice it is important to get the ordering of class and value right when using +`===`. + +We can use these concepts to filter collections down to just those values of a +certain type. We can also ditch those methods and instead use +[`#grep`](https://ruby-doc.org/3.4.1/Enumerable.html#method-i-grep) to pattern +match on the type directly. + +```ruby +> nums = [1, :two, 3.0, 'four', 5, -> { 6 }, 0.7] +=> [1, :two, 3.0, "four", 5, #, 0.7] +> nums.filter { it.is_a?(Numeric) } +=> [1, 3.0, 5, 0.7] +> nums.filter { Integer === it } +=> [1, 5] +> nums.grep(Integer) +=> [1, 5] +> nums.grep(Numeric) +=> [1, 3.0, 5, 0.7] +``` + +[source](https://bsky.app/profile/lucianghinda.com/post/3mhi5xp3xhk25)