Skip to content

Commit 21cca68

Browse files
examples for grep/grep_v methods
1 parent af92a20 commit 21cca68

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

chapters/Arrays.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -767,6 +767,32 @@ Apple
767767
=> [1, 2, 1, 1, 2]
768768
```
769769

770+
* use Enumerable methods `grep` and `grep_v` to filter elements based on `===` operator
771+
* the `===` operator helps to check if an object will satisfy as a member of given condition
772+
* if a block is passed, the given action is performed upon all the filtered elements, similar to `map` method that we'll see later on
773+
* See [stackoverflow: What does the "===" operator do in Ruby?](https://stackoverflow.com/questions/4467538/what-does-the-operator-do-in-ruby) for more details
774+
775+
```ruby
776+
>> arr = [5, 3.14, 'hello', [2, 4], 42, 'bye', -0.3]
777+
=> [5, 3.14, "hello", [2, 4], 42, "bye", -0.3]
778+
779+
>> arr.grep(Integer)
780+
=> [5, 42]
781+
>> arr.grep(String)
782+
=> ["hello", "bye"]
783+
>> arr.grep(3..100)
784+
=> [5, 3.14, 42]
785+
786+
# inverse selection, similar to cli 'grep -v' command
787+
>> arr.grep_v(Float)
788+
=> [5, "hello", [2, 4], 42, "bye"]
789+
>> arr.grep_v(Numeric)
790+
=> ["hello", [2, 4], "bye"]
791+
792+
>> arr.grep(Integer) { |n| n**2 }
793+
=> [25, 1764]
794+
```
795+
770796
* random element(s)
771797

772798
```ruby
@@ -1086,6 +1112,7 @@ ArgumentError (comparison of Integer with String failed)
10861112
* `any?` returns `true` if at least one condition is `true`
10871113
* `none?` returns `true` if all conditions are `false`
10881114
* `one?` returns `true` if exactly one condition is `true`
1115+
* these Enumerable methods use the `===` operator when an argument is passed instead of block
10891116

10901117
```ruby
10911118
>> nums = [4, 2, 51]

0 commit comments

Comments
 (0)