From: Gary Wright Date: 2007-12-09T07:48:46+09:00 Subject: Re: Putting value in sorted array On Dec 8, 2007, at 3:27 PM, Jari Williamsson wrote: > Thanks for the tip! I optimized it into: > > arr = [5, 3, 1] > insert_value = 2 > arr.sort! { |a,b| b <=> a } if !(arr << insert_value).uniq! That is a lot of work to insert an item into a sorted array. Ruby 1.9 has find_index which makes it easy to locate an insert position. Based on that here are some ideas: class Array if RUBY_VERSION < "1.9.0" def find_index(miss=nil) each_with_index { |e,i| return i if yield(e) } miss end end def insert_when(x) pos = find_index { |e| yield(e, x) } insert(pos, x) if pos self end end a = [1,3,5] a.insert_when(4) {|e, x| e >= x } # [1,3,4,5] a.insert_when(4) {|e, x| e >= x } # [1,3,4,4,5] a.insert_when(3) {|e, x| break if e == x e > x } # [1,3,4,4,5]