Hello friends,
Today while programming in ruby and I came to know about the yield word in ruby, how important this word is in ruby, I will discuss some example where to use yield in ruby. As while programming in ruby you must have used blocks and most common usage is to pass the blocks to the method, this method is imperative in ruby's world and you will use it all the time. ruby has special method to handle these type of issues in a easier and faster manner, you can use yield with blocks.
Example of yield:-
def test
puts "Hello test method"
yield
puts "You are again in Hello method"
yield
end
test {puts "You are in the yield"}
Output of the example
You are in the yield
You are again in Hello method
You are in the yield
As you seen in the above example we used yield so it saves us from writing same code several times. you can also use parameters with yield statement.
def test
yield 5
puts "method test"
yield 100
end
test {|i| puts "Example of block #{i}"}
This will produce the following result:
Example of block 5
method test
Example of block 100
Hello test method statement is written followed by parameters. You can even pass more than one parameter. In the block, you place a variable between two vertical lines (||) to accept the parameters. Therefore, in the preceding code, the yield 5 statement passes the value 5 as a parameter to the test block. you can see we have written parameters after yield statement, you can even pass multiple parameters In block variable is placed between (||) two vertical lines for accepting the parameter
0 Comment(s)