Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean to yield within a block?

Tags:

ruby

  def any?
    if block_given?
      method_missing(:any?) { |*block_args| yield(*block_args) }
    else
      !empty?
    end
  end

In this code from ActiveRecord, what is the purpose of a yield statement that exists within a block?

like image 383
uzo Avatar asked Sep 14 '09 05:09

uzo


People also ask

Does yield block?

Using yield enables blocks. We use blocks to pass in bits of code as part of a method call.

What does yield mean in rails?

yield is a keyword in Ruby which allow the developer to pass some argument to block from the yield, the number of the argument passed to the block has no limitations, the main advantage of using yield in Ruby, if we face any situation we wanted to our method perform different functions according to calling block, which ...

What yield means in Ruby?

During a method invocation The yield keyword in corporation with a block allows to pass a set of additional instructions. When yield is called in side a method then method requires a block with in it. A block is simply a chunk of code, and yield allows us to inject that code at some place into a method.

What is block in Ruby?

Similarly, Ruby has a concept of Block. A block consists of chunks of code. You assign a name to a block. The code in the block is always enclosed within braces ({}). A block is always invoked from a function with the same name as that of the block.


1 Answers

Basically if the current method has been given a code-block (by the caller, when it was invoked), the yield executes the code block passing in the specified parameters.

[1,2,3,4,5].each { |x| puts x }

Now { |x| puts x} is the code-block (x is a parameter) passed to the each method of Array. The Array#each implementation would iterate over itself and call your block multiple times with x = each_element

pseudocode
def each
  #iterate over yourself
    yield( current_element )
end

Hence it results

1
2
3
4
5

The *block_args is a Ruby way to accept an unknown number of parameters as an array. The caller can pass in blocks with different number of arguments.

Finally let's see what yield within a block does.

class MyClass
  def print_table(array, &block)
    array.each{|x| yield x}
  end
end

MyClass.new.print_table( [1,2,3,4,5] ) { |array_element| 
    10.times{|i| puts "#{i} x #{array_element} = #{i*array_element}" }
    puts "-----END OF TABLE----"
  }

Here Array#each yields each element to the block given to MyClass#print_table...

like image 50
Gishu Avatar answered Sep 28 '22 16:09

Gishu