I have a code to get list of prime numbers:
def primes_numbers num
primes = [2]
3.step(Math.sqrt(num) + 1, 2) do |i|
is_prime = true
primes.each do |p| # (here)
if (p > Math.sqrt(i) + 1)
break
end
if (i % p == 0)
is_prime = false
break
end
end
if is_prime
primes << i
end
end
primes
end
Is it possible rewrite code using Array methods (select, collect and so on…)?
Something like:
s = (3..n)
s.select { |x| x % 2 == 1}.select{ |x| ..... }
The problem is that I need to iterate throught result array (comment ‘here’) in the select method.
Ruby 1.9 has a very nice
Primeclass:http://www.ruby-doc.org/core-1.9/classes/Prime.html
But I’m assuming you don’t care about any standard classes, but want to see some code, so here we go:
Note: I wrote it this way because you wanted Enumerable methods, for efficiency’s sake you probably want to read up on prime finding methods.