What does the “yield” keyword do in Ruby?

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

    When you write a method that takes a block, you can use the yield keyword to execute the block.

    As an example, each could have been implemented in the Array class like this:

    class Array
      def each
        i = 0
        while i < self.size
          yield( self[i] )
          i = i + 1
        end
      end
    end
    

    MyClass#each takes a block. It executes that block once for each item in the instance's items array, passing the current item as an argument.

    It might be used like this:

    instance = MyClass.new
    instance.items = [1, 2, 3, 4, 5]
    instance.each do |item|
      puts item
    end
    

提交回复
热议问题