for an array like
s = [[1,2],[4,6],[2,7]]
How i can select max and sum of 2nd column in each row in one statement
max= 7
sum= 15
I know, that
sum = 0
max = 0
s.each{ |a,b| sum+=b;if max<b then max = b end }
would work.
The transpose method is nice for accessing "columns":
s = [[1,2],[4,6],[2,7]]
col = s.transpose[1]
p col.max #=> 7
p col.inject(:+) #=> 15
second_elements = s.map { |el| el[1] }
sum = second_elements.inject{|sum,x| sum + x }
max = second_elements.max
To be more clear:
inject{|sum,x| sum + x } returns nil if array is empty, so if you want to get 0 for empty array then use inject(0, :+)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With