Normally blocks are executed in a definition (caller) context
Code:
class A
def initialize
yield
end
end
A.new { p self } #main
With instance_eval it's possible to execute block in callee's (or any other) context:
Code:
class B
def initialize(&block)
instance_eval(&block)
end
end
B.new { p self } #B...
and this is indeed a method tk widgets use:
Code:
require 'tk'
TkLabel.new { p self } # TkLabel...
I don't know if that is a good or bad "practice", but at the first glance it looks confusing. For example, you're unable to use caller's methods inside the block:
Code:
class X
def foo
p "foo"
end
def bar
TkLabel.new { foo() } #doesn't work!
end
end
Bookmarks