Ruby: select, reject, collect. What's the difference?
It will tell you what to choose. With what conditions, for example, only items with a value greater than 3 will be selected, as in the example below.
?
array = [1,2,3,4,5]
array.select { |n| n > 3 }=> [4, 5]
In the example, it will return the value [4,5] only.
Reject
The opposite of Select is that it doesn't take the element, followed by a condition, for example, it doesn't take the element equal to 3.
array = [1,2,3,4,5]
array.reject { |n| n == 3 }=> [1, 2, 4, 5]
Collect
collect is slightly different from the above two in that it returns every value in an array obtained by satisfying the block conditions and puts it in a new array.
array = [1,2,3,4,5]
array.collect { |n| n * 3 }=> [3, 6, 9, 12, 15]?
The example shows the value multiplied by multiplying each (n) in a block by putting them in a new array each round and returning a new value.
1 * 3 = 3
2 * 3 = 6
3 * 3 = 9
4 * 3 = 12
5 * 3 = 15
=> [3, 6, 9, 12, 15]
example
alpha = ['a', 'b', 'c', 'd']
alpha.collect { |c| c.capitalize }=> ["A", "B", "C", "D"]
?
In short version, it will look like this.
alpha = ['a', 'b', 'c', 'd']
alpha.collect(&:capitalize)=> ["A", "B", "C", "D"
It will loop all and change the value to all uppercase.
even if used differently Depends on the picking and use of each job, but in the end all 3 methods will return the same as an array.