Adding every last element in an array of arrays -rails 3

i have an array of arrays such as:-

 a=[["product1", "size1", "color1", "quantity1"],["product2", "size2", "color2", "quantity2"],["product3", "size3", "color3", "quantity3"]]

Now the above Array of arrays has quantity as last element in every array such as quantity1,quantity2,quantity3 and quantity4.i want to add every quantity(last element) to show total quantity *such as quantity1+quantity2+quantity3+quantity4* can i use inject() method,any suggestions??


Have a look at:

total_quantity = a.inject(0){|sum,x| sum + x.last }

Each x is one of your inner arrays. So use last to get the last element of it.

Disclaimer: This works, if your last element in the inner array is a number. As in

a = [["product1", "size1", "color1", 1],["product2", "size2", "color2", 4],["product3", "size3", "color3", 3]]{ |i| i.last.to_i }.inject(:+)

Need Your Help

Return to an already open application when a user tries to open a new instance

c# .net windows

This has been a problem that I haven't been able to figure out for sometime. Preventing the second instance is trivial and has many methods, however, bringing back the already running process isn'...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.