Hi all
number = 0;
objects.each do |o|
number += o.some_number
end
return number
I guess there’s a much more beautiful way for this, or isn’t? Something
like collect or so…
Thanks
Josh
Hi all
number = 0;
objects.each do |o|
number += o.some_number
end
return number
I guess there’s a much more beautiful way for this, or isn’t? Something
like collect or so…
Thanks
Josh
Alle Friday 03 October 2008, Joshua M. ha scritto:
Thanks
Josh
If objects is an array, or any other thing which mixes-in the Enumerable
module, you can use inject:
objects.inject(0){|tot, o| tot + o.some_number}
Stefano
number = 0;
objects.each do |o|
number += o.some_number
end
return numberI guess there’s a much more beautiful way for this, or isn’t? Something
like collect or so…
number = objects.inject(0) { |sum, obj| sum + obj.some_number }
2008/10/3 Joshua M. [email protected]:
Hi all
number = 0;
objects.each do |o|
number += o.some_number
end
return number
This is what inject is for.
number = objects.inject(0) do |sum,o|
sum += o.some_number
end
Farrel
require “facets”
number = objects.map(&:some_number).sum
gegroet,
Erik V.
Is that an echo I hear?
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs