From: Robert Klemme Date: 2009-12-14T01:35:13+09:00 Subject: Re: Code block for element comparison in an array? On 13.12.2009 16:13, Derek Cannon wrote: > Jose Hales-Garcia wrote: >> #method 2 >> a.each_with_index do |e1,i| >> a[(i+1)..a.length].each do |e2| >> # Compare e1 and e2 >> end >> end > > a[(i+1)..a.length].each > ^ That blew my mind Jose! It's a bit inefficient as it will create n intermediate Arrays. Also, the range should be (i+1) ... a.length (i.e. excluding a.length). Here's a variant which does not create all the intermediate sub arrays: a.each_with_index do |e, i| for j in i+1 ... a.length puts "compare #{e} to #{a[j]}" end end Here are more solutions with less math (no "i+1"): a.each_with_index do |e, i| for j in 0 ... i puts "compare #{e} to #{a[j]}" end end a.each_with_index do |e, i| i.times do |j| puts "compare #{e} to #{a[j]}" end end Note, these does compare in a different order. Of course there are a lot more variants... :-) Cheers robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/