Learning Outcome - Monday 16th March, 2020
What learning outcomes did you focus on today? What did you learn
Over the weekend, I spent most of my time Practising more medium level Ruby Algorithm/Katas on Exercism.io. These exercises have enabled me to get more grasp of how Ruby operates behind the scene, understand some Ruby syntax, its application, and TDD. While pairing with my mentor earlier today, he looked at some of my Algorithm solutions and took me through better ways to arrive at a more streamlined solution, this led to a couple of refactoring, writing a lesser line of code to arrive at the same solution. Below are some cool Ruby Syntax/methods and its application.
Inject - Combines all elements of enum by applying a binary operation, specified by a block or a symbol that names a method or operator. If you specify a block, then for each element in enum the block is passed an accumulator value (sum) and the element.
any? - Passes each element of the collection to the given block. The method returns
true
if the block ever returns a value other thanfalse
ornil
. If the block is not given, Ruby adds an implicit block of{ |obj| obj }
that will cause any? to returntrue
if at least one of the collection members is notfalse
ornil
.
Example.
Given a number, find the sum of all the unique multiples of particular numbers up to
but not including that number. My initial solution was;
class SumOfMultiples
def initialize(*multiples)
@multiples = multiples.
end
def to(limit)
result = [ ]
@multiples.each do |multiple|
(1..(limit - 1).each do |range|
if (range % multiple == 0)
result.push(range)
end
end
end
result.uniq.sum
end
end
A better way to streamline the previous solution would be;
class SumOfMultiples
def initialize(*multiples)
@multiples = multiples
end
def to(limit)
(1...limit).inject(0) do |sum, range|
if(@multiples.any?{|multiple| range % multiple == 0})
sum + range
else.
sum
end
end
end
end
The second solution avoids the use of multiple loops and continuous appending of the correct range to the result array before calculating the sum total. Rathers through a binary operation parses an accumulator value (sum) and the element. The enum any? on the other hand, check if certain elements in that array match the criteria in the block.
3. “&” Ampersand parameter - Here’s what the &object does,
If the object is a block, it converts it to a Proc
If the object is a Proc, it converts it to a block
If the object is something else, it calls to Proc on it and then converts it to a block
What’s something that surprises you today?
Anytime you want to do a loop in Ruby, there’s is always a better way to go about it - Doug Bradbury
What’s something that frustrated you today?
The medium level Algorithm/Katas involves a lot of head cracking 😀
Reference