From: Harry Kakueki Date: 2009-10-19T08:00:24+09:00 Subject: Re: Dynamic nested each in ruby 1.8.7? On Mon, Oct 19, 2009 at 6:46 AM, Toi Toi wrote: > That function does not give the correct output for larger arrays. The > level functions can be generated with eval, see the code below. However > there must be a better Ruby way. > > def calc level > tmp = ["def calcd nums\ntmp=[]\n"] > str = "n1" > num = 1 > > level.times { > tmp.push "nums.each{ |n#{num}| tmp.push #{str}\n" > str = str+" + n#{num+=1}" > } > level.times { tmp.push "}"} > > tmp.push "\ntmp\n" > tmp.push "end" > tmp.to_s > end > array, times = ('1'..'10').to_a, 3 > eval(calc(times)) > p calcd(array) > def calc_new(arr,l) h,t = Hash[*(0...arr.size).zip(arr).flatten],[] (1..l).each do |z| (0...arr.size**l).each do |x| t << x.to_s(arr.size).rjust(z,"0") end end t.uniq.sort.map{|c| c.split(//).map{|d| h[d.to_i]}.join} end p calc_new((1..10).to_a, 3) Harry -- A Look into Japanese Ruby List in English http://www.kakueki.com/ruby/list.html