Some important and unknown(least used) ruby methods.
1) inject or reduce
When called, the inject method will pass each element and accumulate each sequentially.
ex:
[1,2,3].inject(:+) => ((1+2)+3)) //we have can any operator here i.e +,-,*,/,%
OR
[1,2,3].inject{|sum, value| sum + value } => 1 iteration: (1 + 2)
=> 2 iteration: (3(1st iteration sum)+3)
we can also pass it a default value or base value for the accumulator.
ex:
[1,2,3].inject(0, :+) => (0+(1+2)+3)) //so here initial value for sum is 0.
We can also use inject menthods for building hash's from the array's
ex:
[[:book, "data structure"], [:price, "400rs"]].inject({}) do |result, element|
result[element.first] = element.last
result
end
#=> {:book=>"data structure", :price=>"400rs"}
ex:2
[[:student, "Terrance Koar"], [:course, "Web Dev"]].inject({}) do |result, element|
result[element.first.to_s] = element.last.split
result
end
# => {"student"=>["Terrance", "Koar"], "course"=>["Web", "Dev"]}
We can also filter the data.
ex:
[10, 20, 30, 5, 7, 9, 3].inject([]) do |result, element|
result << element.to_s if element > 9
result
end
# => ["10", "20", "30"]
We can also find lcm gcm by this
array.inject(:lcm)
2) step
Invokes the given block with the sequence of numbers starting at num, incremented by step (defaulted to 1) on each call.
ex:
1.step.take(4) => [1, 2, 3, 4]
10.step(by: -1).take(4) => [10, 9, 8, 7]
3.step(to: 5) {|i| print i, " " } => 3 4 5 => 3
Comments
Post a comment