Project Euler: #1

I was getting a bit bored so I’ve started Project Eulerhttp://projecteuler.net/ again. I say again, as the last time I tried it I was just starting with learning Haskell. I managed a few of the problems but then I hit a wall.

Since I’m still quite new in the Ruby world (but lapping it up) I gave it another crack. Here’s my first attempt.

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 1000.

answer = 0
(1..999).each do |n|
  answer += n if ( n % 3 == 0 || n % 5 == 0  )

But I knew I could get it done in one line with a fold, all that Haskell didn’t go to waste

#add fold to the available method names because I like it
module Enumerable
  alias :fold inject unless Enumerable.method_defined? :fold

answer = (3..999).fold {|sum, n| (n % 3 ==0 || n % 5 == 0) ? sum + n : sum}
Added on:
Last updated:
Info:Ruby version 1.9.2