What does the “yield” keyword do in Ruby?

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

    A Ruby method that receives a code block invokes it by calling it with the yield keyword. It can be used to iterate over a list but it is not a iterator like what you find in other some other languages.

    Here is a good explanation that explains it better than I would ever be able to.

    0 讨论(0)
  • 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 
    
    0 讨论(0)
提交回复
热议问题