Reputation: 3714
Assume I am supposed to find the sum of multiples of 7 an 9 up to a limit of 255, this is what I do:
(0..255).select do |i|
i % 7 == 0 || i % 9 == 0
end.inject(:+)
I would like to remove the magic numbers and have the method more versatile:
divisors = [7,9,13]
(0..255).select do |i|
divisors.each do |d|
i % d == 0
end
end.inject(:+)
What is an idiomatic way of doing this?
Upvotes: 1
Views: 117
Reputation: 4538
Use Array#map and Enumerable#any?
divisables.map do |d|
i % d == 0
end.any?
HTH
Edit: Alternatively, as @undur_gongor said, you can also use any?
like
divisables.any? { |d| i % d == 0 }
Upvotes: 2