Ruby - Function Nested Methods

Introduction

You can nest methods: write methods that contain other methods.

You can divide a long method into reusable chunks.

Demo

class X
   def outer_x#   ww  w. jav a  2 s.  com
      print( "x:" )
      def nested_y
         print("ha! ")
      end
      def nested_z
         print( "z:" )
         nested_y
      end
      nested_y
      nested_z
   end
end

Nested methods are not initially visible outside the scope in which they are defined.

In the previous example, nested_y and nested_z may be called from inside outer_x, they cannot be called by any other code:

ob = X.new
ob.outer_x         #=> x:ha! z:ha!

When you run a method that encloses nested methods, those nested methods will be brought into scope outside that method!

Demo

class X
  def x#  w  w w  .  j  a  v  a 2s.  c o m
     print( "x:" )
     def y
        print("y:")
     end

     def z
        print( "z:" )
        y
     end
  end
end

ob = X.new
ob.x        #=> x:
puts
ob.y        #=> y:
puts
ob.z        #=> z:y:

Result