From 58e2b326fe99415794308ab57daa52fe0d0d0927 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Wed, 10 Feb 2021 11:35:04 -0600 Subject: [PATCH] Add Exclude Values From An Array as a Ruby til --- README.md | 3 +- ruby/exclude-values-from-an-array.md | 41 ++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 ruby/exclude-values-from-an-array.md diff --git a/README.md b/README.md index a65483a..d30b1a0 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_1041 TILs and counting..._ +_1042 TILs and counting..._ --- @@ -830,6 +830,7 @@ _1041 TILs and counting..._ - [Encode A String As URL-Safe Base64](ruby/encode-a-string-as-url-safe-base64.md) - [Enumerate A Pairing Of Every Two Sequential Items](ruby/enumerate-a-pairing-of-every-two-sequential-items.md) - [Evaluating One-Off Commands](ruby/evaluating-one-off-commands.md) +- [Exclude Values From An Array](ruby/exclude-values-from-an-array.md) - [Expect A Method To Be Called And Actually Call It](ruby/expect-a-method-to-be-called-and-actually-call-it.md) - [FactoryGirl Sequences](ruby/factory-girl-sequences.md) - [Fail](ruby/fail.md) diff --git a/ruby/exclude-values-from-an-array.md b/ruby/exclude-values-from-an-array.md new file mode 100644 index 0000000..908a04f --- /dev/null +++ b/ruby/exclude-values-from-an-array.md @@ -0,0 +1,41 @@ +# Exclude Values From An Array + +In true Ruby fashion, there are all sorts of ways to exclude values from an +array. + +If you just want to exclude `nil` values, you can use +[`#compact`](https://ruby-doc.org/core-3.0.0/Array.html#method-i-compact). + +```ruby +> [1,nil,:what,4].compact +#=> [1, :what, 4] +``` + +If you want to exclude `nil` values and some other named value, you could use +[`#filter`](https://ruby-doc.org/core-3.0.0/Array.html#method-i-filter) or +[`#reject`](https://ruby-doc.org/core-3.0.0/Array.html#method-i-reject). + +```ruby +> [1,nil,:what,4].filter { |val| !val.nil? && val != :what } +#=> [1, 4] +> [1,nil,:what,4].reject { |val| val.nil? || val == :what } +#=> [1, 4] +``` + +The filter is clumsy and heavy-handed for this sort of example. A really terse +way of doing the same thing is with set difference: +[`#-`](https://ruby-doc.org/core-3.0.0/Array.html#method-i-2D). + +```ruby +> [1,nil,:what,nil,5] - [:what,nil] +#=> [1, 5] +``` + +Or the spelled out +[`#difference`](https://ruby-doc.org/core-3.0.0/Array.html#method-i-difference) +method. + +```ruby +> [1,nil,:what,nil,5].difference([:what,nil]) +#=> [1, 5] +```