From: Florian Gross Date: 2004-09-05T22:10:13+09:00 Subject: Re: Style Question Brian Schroeder wrote: > Hello everybody, Moin! > I've got a stylistic question. I know that "the ruby way" to implement > iterations is using .each and similar things, but sometimes I like to use > > for i in 0...n > for j in i...n > do something with i and for > end > end > > Thats nice. > > But if I want to iterate downwards the only way I found is 10.downto(0) do > | i | end What about this: for i in (0...n).to_a.reverse for j in (i...n).to_a.reverse p [i, j] end end The problem with that is that it will be slow for huge ranges. Or maybe this: require 'enumerator' for i in (n - 1).enum_for(:downto, 0) for j in (n - 1).enum_for(:downto, i) p [i, j] end end Or this one: class Range def reverse_each(&block) unless last.respond_to?(:downto) raise(TypeError, "cannot reverse iterate from #{last.class}") end is_first = true last.downto(first) do |item| if is_first and exclude_end? is_first = false next end block.call(item) end end end require 'enumerator' for i in (0...n).enum_for(:reverse_each) for j in (i...n).enum_for(:reverse_each) p [i, j] end end And I think that Range should provide reverse_each in Standard Ruby... (There's no problem in it when using #downto -- it is only defined for Integers, not for Strings.) Regards, Florian Gross