Ruby: Stupid Block Tricks, Part 1

Posted in News by CM8295.Com on the 2007-10-22

The SmallTalk-ish Ruby block syntax is an important part of Ruby.

Proc#binding returns the Binding object — the lexical environment of where the block is created.

The implicit self of the Binding is not normally exposed. It is an important part of execution of the Proc and is useful when defining the semantics of a macro.

Method Binding#_self:

class ::Binding
  # Returns "self" in the context of this Binding.
  def _self
    unless @_self_
      @_self_ = true
      @_self = eval("self", self)
    end
    @_self
  end
end

Example Usage:

 
$blks = [ ]
module ::Kernel
  def take_a_block(&blk)
    $blks << blk
  end
end

take_a_block do 
  puts "#{self.inspect}: A block"
end

class Foo
  take_a_block do
    puts "#{self.inspect}: That block"
  end

  def do_it
    take_a_block do
      puts "#{self.inspect}: This block"
    end
  end
end

Foo.new.do_it

$blks.each do | blk |
  puts "blk.binding._self = #{blk.binding._self}"
  blk.call
end

Generates:

blk.binding._self = main
main: A block
blk.binding._self = Foo
Foo: That block
blk.binding._self = #<Foo:0x100d2030>
#<Foo:0x100d2030>: This block

Comments?

WidgetBucks - Trend Watch - WidgetBucks.com

  1. Responses to “Ruby: Stupid Block Tricks, Part 1”

Post a Comment

captcha