What does it mean to concede in a block?

  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 the yield statement that exists in the block?

+5
source share
3 answers

In principle, if a block code was provided to the current method (calling when it was called), it yieldtransfers the code in the specified parameters.

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

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

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

It follows that

1
2
3
4
5

*block_argsis a Ruby method for accepting an unknown number of parameters as an array. The caller can pass in blocks with a different number of arguments.

Finally, let's see what the result is inside the block.

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----"
  }

Array#each , MyClass#print_table...

+10

. , .

def test_method
  ["a", "b", "c"].map {|i| yield(i) }
end

p test_method {|i| i.upcase }
# => ["A", "B", "C"]

, any?.

+6

This helped me understand: yield- a way to insert blocks into a method that you have already written, which means "execute something here." For example,

No parameter

def original_method
   puts "a"
   puts "b"
end

What if you want to execute some unknown block between the two p?

def updated_method
   puts "a"
   yield
   puts "b"
end

# these two are the same:
updated_method { puts "execute something here" }
updated_method do puts "execute something here" end

Result will be

a
execute something here
b

You can have so much yieldin a method that you like.

With parameter

def updated_method
   puts "a"
   yield
   puts "b"
end

What if you want to execute some unknown block in a line "Execute something on me!"?

def updated_method_with_argument
   puts "a"
   yield("Execute something on me!")
   puts "b"
end

updated_method_with_argument do |argument|
  puts "This argument gets put out: " << argument
end

Result will be

a
This argument gets put out: Execute something on me!
b
0
source

All Articles