What does the “yield” keyword do in Ruby?

后端 未结 8 1644
轮回少年
轮回少年 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:28

    As cpm said its taking the block and executing it

    Simple example:

    def my_method
      yield
    end
    
    
    my_method do
      puts "Testing yield"
    end
    
    Testing yield
    => nil 
    

提交回复
热议问题