Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Ruby Blocks

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 71
    Comment on it

    As we all know,Ruby Blocks and Ruby Methods work in tandem as clearly elucidated by the below example:

    def demo_method
      yield "hello"
    end
    
    demo_method { |block_argument| "#{block_argument}!! our first ruby blog"}

     

    here, the yield keyword within the method finds and invokes the block the method is called with.Alternatively , A less preferred way is to declare a parameter to accept the block in the method signature. Both examples given below are functionally equivalent:

    def second_method &my_block
      my_block.call "argument"
    end
    
    def second_method
      yield "argument"
    end

    Coming back to the earlier example, block_argument  as its name suggests, is the block argument that holds "hello" in this particular case.

     

    Now,consider each method of class Array:

    2.1.5 :005 > ["a","b","c","d"].each {|block_argument| puts block_argument}
    a
    b
    c
    d
     => ["a", "b", "c", "d"] 

     

    It is quite interesting to know the internal implementation of each method ,here it is:

    class Array
      def each
        index = 0 
        while index < self.length 
          yield self[index]
          index += 1
        end
      end
    end

    here , self refers to the current running array object and we pass the current element of the array to the block as its block argument.

    Within a method,in order to check whether the method is being called with a block or not ,we use block_given? method. Depending on the presence or absence of the block ,we can change method behavior accordingly.

    Thanks a lot 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: