From: Stefan Rusterholz Date: 2007-08-25T06:40:51+09:00 Subject: Re: Combining Array Elements Greg Kujawa wrote: > On Aug 24, 9:52 am, "Robert Klemme" > wrote: >> > > [["Value A", "Value B", 3], ["Value A", "Value C", 2],["Value A", >> > > that will suit the task? >> > "Value B", 1]] >> > hash[ elem[0,2] ] += elem[2]; hash }.collect { |k, v| k + [v] } >> => {["Value A", "Value C"]=>2, ["Value A", "Value B"]=>4} >> irb(main):007:0> arr.inject(Hash.new(0)) {|ha,(a,b,c)| >> ha[[a,b]]+=c;ha}.map {|x| x.flatten} >> => [["Value A", "Value C", 2], ["Value A", "Value B", 4]] >> >> At least 1 #inject. :-) >> >> Kind regards >> >> robert- Hide quoted text - >> >> - Show quoted text - > > Thanks guys. All of the insight helps me out tremendously. There are a > lot of abilities that I never tapped into along these lines. Great > stuff and hopefully more tools in my belt. Appreciate the tips! What makes me slightly sad is that all those examples try to squeeze as much as possible into a single statement. Frankly, in my opinion the resulting code is horrible to read again a few months later. I'll try to go a different way, a bit more to type but hopefully easier to read. Maybe somebody has an even more readable idea. array = [["Value A", "Value B", 3], ["Value A", "Value C", 2],["Value A", "Value B", 1]] groups = array.group_by { |element| element.first(2) } result = groups.map { |key, values| values.map! { |a,b,c| c } # if I knew what each value represents I'd chose better names key+[values.sum] } # required code (group_by is in 1.9, though probably a different implementation, sum is in activesupport afaik) module Enumerable def group_by(result=nil, add=nil) result ||= Hash.new { |h,k| h[k]=[] } add ||= :<< each { |args| result[yield(args)].__send__(add, args) } result end end module Enumerable def sum inject(0) { |a,b| a+b } end end Regards Stefan -- Posted via http://www.ruby-forum.com/.