Is there a difference in using `yield self` in a method with` & block` and `yield self` parameters in a method without the` & block` parameter?

I understand that

def a(&block) block.call(self) end 

and

 def a() yield self end 

will produce the same result if I assume that such a block a {} exists. My question is that since I came across some kind of code like this, regardless of whether it has any meaning or if there are any advantages of having (unless I use a variable / link block otherwise case):

 def a(&block) yield self end 

This is a specific case where I do not understand the use of &block :

 def rule(code, name, &block) @rules = [] if @rules.nil? @rules << Rule.new(code, name) yield self end 
+5
source share
2 answers

The only advantage I can think of is introspection:

 def foo; end def bar(&blk); end method(:foo).parameters #=> [] method(:bar).parameters #=> [[:block, :blk]] 

IDEs and documentation generators can take advantage of this. However, this does not affect passing arguments to Ruby. When you call a method, you can pass or omit a block, regardless of whether it is declared or called.

+8
source

The main difference between

 def pass_block yield end pass_block { 'hi' } #=> 'hi' 

and

 def pass_proc(&blk) blk.call end pass_proc { 'hi' } #=> 'hi' 

The idea is that blk , an instance of Proc , is an object and therefore can be passed to other methods. On the contrary, blocks are not objects and therefore cannot be transferred.

 def pass_proc(&blk) puts "blk.is_a?(Proc)=#{blk.is_a?(Proc)}" receive_proc(blk) end def receive_proc(proc) proc.call end pass_proc { 'ho' } blk.is_a?(Proc)=true #=> "ho" 
+1
source

Source: https://habr.com/ru/post/1266682/


All Articles