From: Massimiliano Mirra Date: 2002-01-07T00:15:51+09:00 Subject: [ruby-talk:30349] Re: OT: Re: Sorting a Hash by value of integer stored in the Hash On Sun, Jan 06, 2002 at 09:15:56PM +0900, Michal Rokos wrote: > > Hash[ *ary.flatten ] > OK, this works, but let's imagine another ex.: > a = [[1,[2,3]],[4,[5,6]]] > I want {1=>[2,3], 4=>[5,6]}, not {1=>2, 3=>4, 5=>6}... :-) Well, so you'll have to convert it to something acceptable from Hash constructor, won't you? ;-) old = [[1,[2,3]],[4,[5,6]]] new = [] old.each {|item| new.concat item} Hash[*new] Something more general: class Array # Flatten n levels (one by default) # def flatten2(level = 1) flattened = [] each do |item| if item.kind_of?(Array) flattened.concat item else flattened.push item end end flattened = flattened.flatten2(level-1) if level > 1 return flattened end end if $0 == __FILE__ require 'Lapidary/TestCase' class TestArray < Lapidary::TestCase def testFlattenLevel1 a = [[1,[2,3]], [4,[5,6]]] assert_equal [1, [2, 3], 4,[5, 6]], a.flatten2 end def testFlattenLevel2 a = [[1, [2, 3]], [4, [5, 6]]] assert_equal [1, 2, 3, 4, 5, 6], a.flatten2(2) end def testFlattenLevelN a = [[1, [2, [3, 4]]], [5, [6, [7, 8]]]] assert_equal [1, [2, [3, 4]], 5, [6, [7, 8]]], a.flatten2 assert_equal [1, 2, [3, 4], 5, 6, [7, 8]], a.flatten2(2) assert_equal [1, 2, 3, 4, 5, 6, 7, 8], a.flatten2(3) end end require 'Lapidary/UI/Console/TestRunner' Lapidary::UI::Console::TestRunner.run(TestArray) end I hope nobody minds me posting tests along with snippets. They take more bandwidth but I find them easier to understand than explanations, however well crafted they are. Massimiliano