What does the “yield” keyword do in Ruby?

后端 未结 8 1722
轮回少年
轮回少年 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条回答
  •  -上瘾入骨i
    2020-12-24 02:04

    According to my understanding yield executes code from block.

    def name
        puts "A yield will be called with id of 12"
        yield 12
        puts "A yield will be called with id of 14"
        yield 14
    end
    
    
    name {|i| puts "I am called by yield name #{i}"}
    

    Output:

    A yield will be called with id of 12

    I am called by yield name 12

    A yield will be called with id of 14

    I am called by yield name 14

    How yield works?

    So when the name function runs wherever yield comes the block code runs. Which is name {|i| puts "I am called by yield name #{i}"}

    You can see that there is a word yield 12 yield runs the code inside block passing 12 as value of i.

    Here is a game example for it:

    def load_game
        puts "Loading"
    
        yield
    
    end
    
    
    load_game { puts "Game loaded" }
    

    This will print game loaded right after printing loading:

    Loading

    Game Loaded

提交回复
热议问题