I encountered the following Ruby code:
class MyClass
attr_accessor :items
...
def each
@items.each{|item| yield item}
end
...
end
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