C
Chandramouli Parasuraman
Hi,
I'm new to ruby, and I am trying to add all the natural numbers below
one thousand that are multiples of 3 or 5. (exercise from ProjectEuler)
Here's my code:
class Array
def sumNumbers
sum = 0
self.each_with_index { |n, i|
if ((self % 3) == 0 || (self % 5) == 0)
sum += self
end
}
sum
end
end
numbers = [1..1000]
print "Sum of natural numbers till 1000 that are multiples of 3 or 5 is
" + numbers.sumNumbers
When I try to execute this, I get this error:
SumOfMults.rb:5:in `block in sumNumbers': undefined method `%' for
1..1000:Range
(NoMethodError)
from SumOfMults.rb:4:in `each'
from SumOfMults.rb:4:in `each_with_index'
from SumOfMults.rb:4:in `sumNumbers'
from SumOfMults.rb:14:in `<main>'
Not sure how self is actually treated as a Range. Can you please let
me know what's wrong in my code?
Thanks,
Mouli
I'm new to ruby, and I am trying to add all the natural numbers below
one thousand that are multiples of 3 or 5. (exercise from ProjectEuler)
Here's my code:
class Array
def sumNumbers
sum = 0
self.each_with_index { |n, i|
if ((self % 3) == 0 || (self % 5) == 0)
sum += self
end
}
sum
end
end
numbers = [1..1000]
print "Sum of natural numbers till 1000 that are multiples of 3 or 5 is
" + numbers.sumNumbers
When I try to execute this, I get this error:
SumOfMults.rb:5:in `block in sumNumbers': undefined method `%' for
1..1000:Range
(NoMethodError)
from SumOfMults.rb:4:in `each'
from SumOfMults.rb:4:in `each_with_index'
from SumOfMults.rb:4:in `sumNumbers'
from SumOfMults.rb:14:in `<main>'
Not sure how self is actually treated as a Range. Can you please let
me know what's wrong in my code?
Thanks,
Mouli