To answer Euler's question:
(1 ... 1000).to_a.select{|x| x%3==0 || x%5==0}.reduce(:+)
Sometimes a single-line font is more readable than the more verbose code that I think.
Assuming you are learning Ruby with ProjectEuler examples, I will explain what the line does:
(1 ... 1000).to_a
will create an array with numbers from 1 to 999. Euler-Question wants numbers below 1000. Using three points in the range will create it without the most boundary value.
.select{|x| x%3==0 || x%5==0}
selects only those elements that are divisible by 3 or 5 and therefore multiplied by 3 or 5. The remaining values ββare discarded. The result of this operation is a new array with short values ββof 3 or 5.
.reduce(:+)
Finally, this operation sums all the numbers in the array (or reduces them) by one number: the amount needed to solve.
What I want to illustrate: many of the methods that you write manually every day are already integrated into the ruby, as it is a programmer language for programmers. be pragmatic;)
source share