Multiples of 3 and 5 Project Euler problem #1:


  If we list all the natural numbers below 10 that are multiples of 3 or
  5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
  
  Find the sum of all the multiples of 3 or 5 below N.


My code is correct, but I don't know how I can optimize and make that faster.

N = gets.to_i
N.times do 
  arr = []
  (0...gets.to_i).each { |j| arr &lt;&lt; j if j % 3 == 0 || j % 5 == 0 }
  puts arr.reduce(:+)
end
You use a constant N as your variable... not dreadful, but a little confusing.

You first ask the user for how many times they want to run the code, then for which number to sum the mods of 3 &amp; 5 for; it would be simpler to just write the code which asks for a number and works the sum - if the user wants to run it multiple times, then let them! :-)

No need to start at zero - 0,1, &amp; 2 are never going to be divisible by three (although we'd need to add some validation in case the user adds a very low number)

Instead of setting up an intermediate arr value and iterating with each, you can select to get the numbers that return true for the block.

But your main question is about speed - have you benchmarked your code to find out if the speed is an issue?

n = gets.to_i
return 0 unless n &gt; 2 # you could do this as a ternary or `if` statement if you prefer
(3...n).select { |j| j % 3 == 0 || j % 5 == 0 }.reduce(:+)