How does the yield magic work in ActionView?

后端 未结 3 1586
名媛妹妹
名媛妹妹 2021-01-14 14:55

I was looking at how content_for works and observed the block.call in the capture_erb_with_buffer method. It apparently magically writes to the buf

3条回答
  •  攒了一身酷
    2021-01-14 15:26

    Simply:

    calling yield in a method executes code that was passed to the method via a block.

    For instance

    def my_method
      yield
    end
    
    my_method { puts "Hello" }
    my_method { puts "World" }
    

    these 5 lines will produce the following output to the screen

    Hello
    World
    

    See the following page for a nice discussion of yield in Ruby: Ruby Yield

提交回复
热议问题