Skip to content

Commit 58e2b32

Browse files
committed
Add Exclude Values From An Array as a Ruby til
1 parent 8ed1655 commit 58e2b32

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
1212

13-
_1041 TILs and counting..._
13+
_1042 TILs and counting..._
1414

1515
---
1616

@@ -830,6 +830,7 @@ _1041 TILs and counting..._
830830
- [Encode A String As URL-Safe Base64](ruby/encode-a-string-as-url-safe-base64.md)
831831
- [Enumerate A Pairing Of Every Two Sequential Items](ruby/enumerate-a-pairing-of-every-two-sequential-items.md)
832832
- [Evaluating One-Off Commands](ruby/evaluating-one-off-commands.md)
833+
- [Exclude Values From An Array](ruby/exclude-values-from-an-array.md)
833834
- [Expect A Method To Be Called And Actually Call It](ruby/expect-a-method-to-be-called-and-actually-call-it.md)
834835
- [FactoryGirl Sequences](ruby/factory-girl-sequences.md)
835836
- [Fail](ruby/fail.md)

ruby/exclude-values-from-an-array.md

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Exclude Values From An Array
2+
3+
In true Ruby fashion, there are all sorts of ways to exclude values from an
4+
array.
5+
6+
If you just want to exclude `nil` values, you can use
7+
[`#compact`](https://ruby-doc.org/core-3.0.0/Array.html#method-i-compact).
8+
9+
```ruby
10+
> [1,nil,:what,4].compact
11+
#=> [1, :what, 4]
12+
```
13+
14+
If you want to exclude `nil` values and some other named value, you could use
15+
[`#filter`](https://ruby-doc.org/core-3.0.0/Array.html#method-i-filter) or
16+
[`#reject`](https://ruby-doc.org/core-3.0.0/Array.html#method-i-reject).
17+
18+
```ruby
19+
> [1,nil,:what,4].filter { |val| !val.nil? && val != :what }
20+
#=> [1, 4]
21+
> [1,nil,:what,4].reject { |val| val.nil? || val == :what }
22+
#=> [1, 4]
23+
```
24+
25+
The filter is clumsy and heavy-handed for this sort of example. A really terse
26+
way of doing the same thing is with set difference:
27+
[`#-`](https://ruby-doc.org/core-3.0.0/Array.html#method-i-2D).
28+
29+
```ruby
30+
> [1,nil,:what,nil,5] - [:what,nil]
31+
#=> [1, 5]
32+
```
33+
34+
Or the spelled out
35+
[`#difference`](https://ruby-doc.org/core-3.0.0/Array.html#method-i-difference)
36+
method.
37+
38+
```ruby
39+
> [1,nil,:what,nil,5].difference([:what,nil])
40+
#=> [1, 5]
41+
```

0 commit comments

Comments
 (0)