What does the “yield” keyword do in Ruby?

后端 未结 8 1719
轮回少年
轮回少年 2020-12-24 01:22

I encountered the following Ruby code:

class MyClass
    attr_accessor :items
    ...
    def each
        @items.each{|item| yield item}
    end
    ...
end         


        
8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-24 02:24

    As a newbie, looking through a number of the answers confused me until I hit Abhi's answer.

    the yield command pauses executing the code in the method, and instead passes control back to the block of code that called it, executes that code, and then continues executing the rest of the method after that. Here's an example that clarified it for me:

    def hello
        puts "hello"
        yield 
        puts "world"
    end
    
    hello do
        puts "there"
    end 
    

    Output:

    hello

    there

    world

提交回复
热议问题