From: botp Date: 2010-05-14T10:58:03+09:00 Subject: Re: Putting value in sorted array On Sun, Dec 9, 2007 at 1:48 AM, Jari Williamsson wrote: > arr = [5, 3, 1] > insert_value = 2 > > arr.each_index {|v, i| >   break if v == insert_value >   if insert_value > v >      arr.insert(i, insert_value) >      break >   end > } 1 that breaks if value inserted is less than minimum 2 inserting/modifying while walking the array may not be defined for ruby > Is there a "simpler" solution? your scheme is clear and simple enough, just fix some edge cases... then you'll be ready for your newly special insert method eg, ?> class Array >> def insert2 value >> pos=self.size >> existing=false >> each_with_index do |v, i| ?> if v == value >> existing=true >> break >> elsif value > v >> pos=i >> break >> end >> end >> insert(pos,value) unless existing >> end >> end => nil >> ?> ?> arr = [5, 3, 1] => [5, 3, 1] >> arr.insert2 6 => [6, 5, 3, 1] >> arr.insert2 2 => [6, 5, 3, 2, 1] >> arr.insert2 0 => [6, 5, 3, 2, 1, 0] >> arr.insert2 3 => nil >> arr => [6, 5, 3, 2, 1, 0] best regards -botp