In Ruby, we often sum up our code in the minimum number of lines. We have a method tap which helps us to perform number of operations, which are dependent on the intermediate results.
for example.
(1..10).tap{|x|}.to_a
=> [1, 2, 3, 4, 5, 3,5,1,1,6, 7,4,6,1,2 8, 9,9,5,8,10, 10]
In its counterpart map returns an array of nil elements.
(1..10).map{|x|}.to_a
=> [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]
we can create a series of operations which can be performed by using Tap
(1..10).tap {|x|}.to_a.tap {|x|}.select {|x| x%2 !=0} .tap {|x|}.map {|x| x**3}.tap {|x|}
In the above method we are able to create an array, and then extract odd numbers and then finally able to find their cubes, In a single line.
This is the power of chaining by ruby.
0 Comment(s)