1
0
mirror of https://github.com/jbranchaud/til synced 2026-07-03 16:18:24 +00:00

Add Filter By Type as a Ruby TIL

This commit is contained in:
jbranchaud
2026-03-20 09:18:10 -05:00
parent 16082177aa
commit 329ce1aa3e
2 changed files with 39 additions and 1 deletions
+2 -1
View File
@@ -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). 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: 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) - [FactoryGirl Sequences](ruby/factory-girl-sequences.md)
- [Fail](ruby/fail.md) - [Fail](ruby/fail.md)
- [Fetch Warns About Superseding Block Argument](ruby/fetch-warns-about-superseding-block-argument.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) - [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) - [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) - [Format A Hash Into A String Template](ruby/format-a-hash-into-a-string-template.md)
+37
View File
@@ -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, #<Proc:0x0000000123af0338 (irb):5 (lambda)>, 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)