Array Manipulations in Ruby
We will be discussing some built-in functions in Ruby. Most of them are used to fix logical challenges in Ruby Programming. Let's look at each of them
select
- Used to filter the collections.
- Return type will be an array.
[1, 2, 3, 4, 5].select{ |i| i > 3 }
#=> [4, 5]
detect
- Will return the first matched value
- The returned value will be a single element
[1, 2, 3, 4, 5].detect{ |i| i > 3 }
#=> 4
reject
- Will be the opposite of the select
- Will be an array
[1, 2, 3, 4, 5].reject{ |i| i > 3 }
#=> [1, 2, 3]
Equality Operator
- Denoted by “===”
- More used in the case of Regex and range
(1..3) === 2
#=> true(1..3) === 4
#=> false/el/ === ‘Hello World’
#=> false
- LHS should be Range or REGEX and RHS will be the specific object.
grep
- Same use in the case of grep
[6, 14, 28, 47, 12].grep(5..15)
#=> [6, 14, 12]
- We have an array like `[1, ‘a’, ‘b’, 2]`
- If we do the `[1, ‘a’, ‘b’, 2].map(&:upcase)`
- Will raise an error
- We can fix those by grep
[1, ‘a’, ‘b’, 2].grep(String, &:upcase)
#=> [‘A’, ‘B’]
sort
- If we have integer and strings in the array .sort command will fail.
- We can clear this issue by using the sort_by method.
[‘5’, ‘2’, 3, ‘1’].sort_by(&:to_i)
#=> [‘1’, ‘2’, 3, ‘5’]
all?
- Return true if all values are true
[2, 4, 6, 8].all?(&:even?)
#=> true
any?
- Return true if any of the value is true.
[2, 3, 5, 9].any?(&:even?)
#=> true
reduce
- Create a sum of the array
[1, 2, 3].reduce(:+)
#=> 6
other interested methods are cycle, next, reverse_cycle