Search code examples
rubyrecursionblockbubble-sort

Passing a block to a method recursively in ruby


def bubble_sort_by nums
  do_it_again = false
  nums[0...-1].each_with_index do |item, index|
    if yield(nums[index], nums[index + 1]) > 0
      nums[index], nums[index + 1] = nums[index + 1], nums[index]
      do_it_again = true
    end
  end
  bubble_sort_by nums if do_it_again
  nums
end

bubble_sort_by(["hi","hello","hey"]) do |left,right|
  right.length - left.length
end

Program does a bubble sort based on a block. In this case, the block sorts by length. So, I get a local jump error. Took me a bit, but I figured it out. When I call the method recursively, I'm not giving it the block. But how do I do that?


Solution

  • Passing the block is optional, but here, as you already understood, you need it to make your recursive calls. You just pass the block as an additional parameter:

    def bubble_sort_by nums, &comparator
      # ...
      bubble_sort_by nums, &comparator if do_it_again
      # ...
    end