From: Chandramouli Parasuraman Date: 2010-05-04T19:59:32+09:00 Subject: Calculation in a block 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[i] % 3) == 0 || (self[i] % 5) == 0) sum += self[i] 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 `
' Not sure how self[i] is actually treated as a Range. Can you please let me know what's wrong in my code? Thanks, Mouli -- Posted via http://www.ruby-forum.com/.