title: Finding next smallest number with same digits
body: <p>I'm working with Ruby and trying to write a code that will take a numerical input and return the next biggest number with the same digits.  </p>
  
  <p>I have seen this same question asked here before but the code differs too much to help me solve my particular problem.</p>
  
  <pre><code>def next_smaller n
    ndigitsarray=n.digits.reverse
    bigdigitsarray=ndigitsarray.sort.reverse
    bigdigitsjoint=bigdigitsarray.join.to_i
      while bigdigitsjoint&gt;n do 
    bigdigitsarray.insert(1, bigdigitsarray.delete_at(0)) 
      end
    return bigdigitsarray.join.to_i
  end
  </code></pre>
  
  <p>The code times out; I am not sure why it isn't looping correctly. Any help would be gratefully received!</p>
  
  <p>EDIT - I have worked out why there is an infinite loop, but I am leaving this up for now in case anyone has any suggestions for solving the larger problem!</p>