From: Jari Williamsson Date: 2007-12-09T05:27:28+09:00 Subject: Re: Putting value in sorted array yermej wrote: > 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! 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! (Only sorts on no-duplicate and sort in correct direction first time around.) Best regards, Jari Williamsson