What does the “yield” keyword do in Ruby?

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

    yield tells ruby to call the block passed to the method, giving it its argument.

    yield will produce an error if the method wasn't called with a block where as return statement don't produces error.

    return can only send single values where as Yield return object of huge values.

提交回复
热议问题