title: In Ruby, use a function defined within a method
body: <p>As part of an exercise, I'm trying to implement the bubble sort algorithm in two different ways.</p>
  
  <p>For the first part, I've implemented the bubble sort algorithm as an Array instance method as follows:</p>
  
  <pre><code>class Array
    def bubble_sort!
      sorted=false
      until sorted
        sorted=true
        for i in (0...self.length-1)
          if self[i]&gt;self[i+1]
            self[i],self[i+1]=self[i+1],self[i]
            sorted=false
          end
        end
      end
      self
    end
  end
  </code></pre>
  
  <p>so that, for example,</p>
  
  <pre><code>[5,2,4].bubble_sort!
  </code></pre>
  
  <p>returns [2,4,5]. The next part of the exercise is to modify the method so that it takes a block to perform the comparison:</p>
  
  <pre><code>[1, 3, 5].bubble_sort! { |num1, num2| num1 &lt;=&gt; num2 } #sort ascending
  [1, 3, 5].bubble_sort! { |num1, num2| num2 &lt;=&gt; num1 } #sort descending
  </code></pre>
  
  <p>In order to not repeat myself, I've tried to implement this as follows:</p>
  
  <pre><code>class Array
    def bubble_sort!(&amp;prc)
      if block_given?
        boolean_operator = Proc.new {|a,b| prc.call(a,b)==1}
      else
        boolean_operator = Proc.new {|a,b| a&gt;b}
      end
  
      sorted=false
      until sorted
        sorted=true
        for i in (0...self.length-1)
          # if self[i]&gt;self[i+1]
          if boolean_operator(self[i],self[i+1])
            self[i],self[i+1]=self[i+1],self[i]
            sorted=false
          end
        end
      end
      self
    end
  </code></pre>
  
  <p>However, if I try to test this with</p>
  
  <pre><code>p [5,2,4].bubble_sort! {|x,y| x&lt;=&gt;y}
  </code></pre>
  
  <p>I get the following error:</p>
  
  <pre><code>in `bubble_sort!': undefined method `boolean_operator' for [5, 2, 4]:Array (NoMethodError)
  </code></pre>
  
  <p>It seems like the "boolean_operator" is somehow not defined where it is invoked (also not if I remove the block in the input). I understand that Ruby doesn't have nested methods, but I thought that defining procs and lambdas within a method was possible?</p>