Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • yield in ruby

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 351
    Comment on it

    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:-

    1. def test
    2. puts "Hello test method"
    3. yield
    4. puts "You are again in Hello method"
    5. yield
    6. end
    7. test {puts "You are in the yield"}

     

    Output of the example

    1. You are in the yield
    2. You are again in Hello method
    3. 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.

    1. def test
    2. yield 5
    3. puts "method test"
    4. yield 100
    5. end
    6. test {|i| puts "Example of block #{i}"}

     

    This will produce the following result:

    1. Example of block 5
    2. method test
    3. 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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: