Dinamically adding methods to objects using blocks
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.