February 2, 2004 Intro to Ruby Slide #28
Prev Next

Enumerable

     module Enumerable
       def bubble_sort
         a = self.dup.to_a
         0.upto(a.length-2) do |i|
           0.upto(a.length-2-i) do |j|
             if yield(a[j+1], a[j]) == -1  # comparison block is passed in
               a[j], a[j+1] = a[j+1], a[j]
             end
           end
         end
     
         return a
       end
     
     end
     
     f = %w(apple peach rhubarb blueberry pumpkin)
     f_sorted = f.bubble_sort{|a,b| a<=>b}


Prev Copyright © 2004 Walter C. Mankowski Next