Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Ronie Uliana mecanicamente.blogspot.com

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Dinamically adding methods to objects using blocks

(Modified version of http://www.thekode.net/ruby/techniques/DefiningMethodsWithClosures.html)
You can dinamically define a method in an instance using the following code:

   1  
   2  class Object
   3    def def(method_name, &block)
   4      (class << self; self end).send(:define_method, method_name, block)
   5    end
   6  end
   7  
   8  x = Object.new
   9  
  10  string = "This is a test"
  11  x.def(:testing_a_block) {puts string + "!"}
  12  
  13  x.testing_a_block


Maybe you could also use:

   1  
   2  x = Object.new
   3  class << x
   4    def testing_no_block
   5      puts string + "!"
   6    end
   7  end
   8  
   9  x.testing_no_block


But there is a difference, run both codes and you will see. The second version doesn't use a block, so it has no access to the variables where the block was created.
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS