Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • using return keyword within a Ruby block

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 376
    Comment on it

    As we all know,Ruby Blocks and Ruby Methods work in tandem and the output/value of the last line/expression being executed by the block is returned to the associated method .

    Have a look at this example:

    2.1.5 :006 > def demo
    2.1.5 :007?>   puts yield
    2.1.5 :008?>   end
     => :demo 
    2.1.5 :009 > demo { "hello!"}
    hello!
     => nil

    here,the yield keyword within the method finds and invokes the block the method is called with and the block returns a string object namely "hello" and method simply prints it.

    Now,coming to the inherent subtleties of using return keyword within the body of  a Ruby block ,the use of return keyword isn't recommendable because instead of returning from the block itself ,it returns from the method where the block is being defined .

    Have a look at this below given example:

    def first_method
      puts yield
    end
    
    def second_method
      first_method { "hello"}
    end
    
    second_method

    When we call second_method  it prints hello.

    Now a slight change in code:

    def first_method
      puts yield
    end
    
    def second_method
      first_method { return "hello"}
    end
    
    second_method
    
    

    now,it won't print anything because the return keyword instead of returning the last expression executed ,returns from the body of second_method where the block is being defined.

    So at last for recapitulation ,we can pass parameters to a block or use the return value from the block or both or neither.For example ,the each  method simply ignores the return value from its blocks.

    Thanks for Reading.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: