How it works with Proc object?

def test
yield
end

test do
p “a”
end

i dont know how yield function does in detail. why did i write yield and then the p 'a' works? i know that it is a Proc object , but i dont know how it works. Is Proc do as a parameter?
test do
p “a”
end
and is this code which makes the output?
thanks a lot.

All Ruby methods have an invisible implicit block parameter. That
means that the signature of #test really looks like this:

def test(&block)
  # ...
end

When you write “yield”, you’re saying, “call the block that was passed
to this method”, so #test looks like this:

def test(&block)
  call &block and evaluate it
end

That means that if you call #test with { p “a” }, then #test’s
implementation is effectively

def test
  p "a"
end

~ jf

John F.
Principal Consultant, BitsBuilder
LI: http://www.linkedin.com/in/johnxf
SO: User John Feminella - Stack Overflow

On Sep 6, 1:47pm, John F. [email protected] wrote:

That means that if you call #test with { p “a” }, then #test’s
implementation is effectively

def test
 p "a"
end

With the difference that the block executes with access to the local
variables, value of self etc. that were present where the block was
defined

Fred

felix wrote in post #1020377:

def test
yield
end

In addition to John F.'s excellent explanation, note that your
definition of test() requires that a block be specified when calling
test():

def test
yield
end

test()

–output:–
ruby.rb:2:in test': no block given (yield) (LocalJumpError) from ruby.rb:5:in

Typically test() would be defined like this:

def test
if block_given?
yield #i.e. execute the block
else #do something else
puts “goodbye”
end
end

test()

–output:–
goodbye

Also note, you can capture the block in a variable:

def test(&var_name) #& means put the block in this var
if block_given?
another_method(var_name)
else
puts “goodbye”
end
end

def another_method(x)
x.call #execute the block
end

test do
puts ‘hello’
end

–output:–
hello