Skip to main content

Ruby Blocks

Block is extremely powerful feature in ruby programming. By using of block, there are possible to write complex code in very easy manner. Block is parallel to method which can be pass to method as argument. And inside the method there is possible to execute of passing block.

method_name{#block statements}
#When method are accept parameter list
method_name(parameter_list) {#block statements}

Block is like a piece of codes. which can be executing instruction and returning values, and accepted parameter list as well. parameter and return statement is optional. Very interesting that, this have no name. and it doesn't belongs to any objects. Let see an example.

=begin  
  Example of blocks
=end  
def execute_block

  #Execute block statement 
  yield
  puts 'Method Statement'  
  # Execute block statement  
  yield  
  puts 'Method Statement' 
  # Execute block statement  
  yield  
end  
#execute method
execute_block {puts 'Test Block Data'}  
Test Block Data
Method Statement
Test Block Data
Method Statement
Test Block Data

when method are passing values to blocks

def test
  puts "Start Method Execution"
    #send value to block
    yield(2,3)
    yield(5,3)
  puts "End Method Execution"

end  
#execute method
test{  
  #accepting values parameters
  |first,second| 
  #display get value
  puts "First: #{first}  Second : #{second}"
}  
Start Method Execution
First: 2  Second : 3
First: 5  Second : 3
End Method Execution

Check block are given

def test
  puts "\nStart Method Execution"
    if block_given?
      puts "Block is Given"
      #send value to block
      yield(2,3)
      yield(5,3)
    else
      puts "Block is not Given"
    end 
  puts "End Method Execution"

end  

#when no block
test 


#execute method
test{  
  #accepting values parameters
  |first,second| 
  #display get value
  puts "First: #{first}  Second : #{second}"
}  
Start Method Execution
Block is not Given
End Method Execution

Start Method Execution
Block is Given
First: 2  Second : 3
First: 5  Second : 3
End Method Execution

Another way to execute block

def test(&fun)
  fun.call("Joly")
  fun.call("Smith")

end  
test {|info| puts  "Hi #{info}"}
Hi Joly
Hi Smith
def execute_block

  yield(10,20)
  proc.call(30,40)
  Proc.new.call("A","B")

end  
#execute method
execute_block {|first,second| 
  puts "#{first}  #{second}"}  
10  20
30  40
A  B

BEGIN,END Blocks

#Main execution
puts "Debug Code"

END { 
   # END block 
   puts "Run code"
}

BEGIN { 
   # BEGIN Block 
   puts "Check Logic Error"
} 
Check Logic Error
Debug Code
Run code




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment