1> 'each' will loop through each element of the array and evaluate whatever is return inside the block, but it returns the original array without any change.
a = [5,10,15,20]
=> [5, 10, 15, 20]
a.each {|t| t+2}
=> [5, 10, 15, 20]
a.each {|t| puts(t+2)}
7
12
17
22
=> [5, 10, 15, 20]
(Thus we see that whatever is written inside the each block is evaluated and the original array is returned at the end)
2>'collect' returns the new array which is created as the result of executing the specified block for every item of the given array.
a = [1,2,3,4]
a.object_id
=> 76272700
a.collect {|x| x*3}
=> [3, 6, 9, 12]
a.object_id
=>76337640
puts a
=> [1, 2, 3, 4]
(Thus we can see collect returns a new array after performing the operations defined in the block on each element of original array, leaving the original array intact)
3> 'map' is similar to 'collect'. There is no specific difference between them in functionality, both of them perform the same thing
c = [1,2,3,4]
=> [1, 2, 3, 4]
c.object_d
=> 76350610
c.map {|x| x*5}
=> [5, 10, 15, 20]
p c.object_id
=> 76350610
p c
=> [1, 2, 3, 4]
(Thus we can see map also returns a new array after performing the operations defined in the block on each element of original array, leaving the original array intact)
0 Comment(s)