From: yermej Date: 2007-12-09T04:55:00+09:00 Subject: Re: Putting value in sorted array On Dec 8, 11:48 am, Jari Williamsson wrote: > I have an array that's sorted from highest value to lowest. I also want > to insert a value in sort order, but only if the value doesn't exist > already. I ended up with a solution (writing from memory here, it was on > another computer) that feels a bit "long" for Ruby code, going something > like this: > > --- > 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} > > --- > > Is there a "simpler" solution? > > Best regards, > > Jari Williamsson I guess it depends on how much efficiency you need. You could always do: arr = [5, 3, 1] insert_value = 2 (arr << insert_value).uniq! arr.sort!.reverse!