Lawleyenda
Lawleyenda

Reputation: 75

How Yield statement in ruby works?

Can someone please show how to correctly format this yield statement, and why my methodology for this yield statement is incorrect? When run, the compiler results in an "undefined method 'length' error. "Test" is the main class.

  def bubble_sort_by(array)
    len = array.length - 1
    while len > 0
      for i in(1..len)
        @left = array[i]
        @right = array[i - 1]
        yield
        if @left - @right > 0
           array[i - 1], array[i] = array[i], array[i - 1]
        end
      end
      len -= 1
    end
   p array
end

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

Upvotes: 0

Views: 182

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110675

As I said in my comment on the question, yield needs to pass values for the block variables. Your code therefore needs to be modified as follows.

def bubble_sort_by(array)
    len = array.length - 1
    while len > 0
      for i in(1..len)
        @left = array[i]
        @right = array[i - 1]
        if yield(@left, @right) > 0
          array[i - 1], array[i] = array[i], array[i - 1]
        end
      end
      len -= 1
    end
  array
end

bubble_sort_by(%w[hi hello hey]) do |left, right|
  left.length - right.length
end
  #=> ["hello", "hey", "hi"]

If, as here, the block being yielded to has block variables, the values of those variables must be passed as yield's arguments. The value computed by the block is then returned as though yield were the invocation of a method.

If you prefer, you could replace the first line with

def bubble_sort_by(array, &block)

and replace if yield(@left, @right) > 0 with

if block.call(@left, @right) > 0

Here & converts the bloc to a Proc which is held by the variable block.

Upvotes: 2

DonPaulie
DonPaulie

Reputation: 2214

because you need to pass arguments to yield.

try to change the line with yield into: compared = yield @left, @right and deal with the compared result

Upvotes: 2

Related Questions