Rewrite simple ruby function to use a block Rewrite simple ruby function to use a block ruby ruby

Rewrite simple ruby function to use a block


You can define Dwg's initializer to take a block, and then yield to that block with instance_eval, like so:

class MyClass  def initialize(name, &block)    @name = name    instance_eval &block  end  def show_name    puts 'My name is ' + @name  endendMyClass.new('mud') do  show_nameend# >> My name is mud

For more information, see the "Blocks for Interface Simplification" section in the recently Creative-Commons-licensed Chapter 2 of Gregory Brown's excellent Ruby Best Practices book. (Its author and publisher are gradually CCing the entire thing, but you can of course still buy a copy to support the work. The iPhone edition is particularly affordable.)