Forum: Ruby Binding Blocks? (in Tk, for example)

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Mat S. (Guest)
on 2006-05-26 17:39
(Received via mailing list)
So I was playing with ruby-tk and this syntax really suprised me:

TkLabel.new {
	text "Hello, World"
	pack ...
}

'text' isn't available outside the block, so I assume the function is
getting evaulated in TkLabel's scope?

How does TkLabel pull the block into it's internal scope?

Thanks,
Mat
ts (Guest)
on 2006-05-26 17:42
(Received via mailing list)
>>>>> "M" == Mat S. <removed_email_address@domain.invalid> writes:

M> How does TkLabel pull the block into it's internal scope?

 it use instance_eval

Guy Decoux
Mat S. (Guest)
on 2006-05-26 17:48
(Received via mailing list)
On May 26, 2006, at 9:40 AM, ts wrote:
>>>>>> "M" == Mat S. <removed_email_address@domain.invalid> writes:
>
> M> How does TkLabel pull the block into it's internal scope?
>
>  it use instance_eval

Can you give a code example or documentation page?  I can't figure
out how to use instance_eval with a Proc or yield...
-Mat
ts (Guest)
on 2006-05-26 17:55
(Received via mailing list)
>>>>> "M" == Mat S. <removed_email_address@domain.invalid> writes:

M> Can you give a code example or documentation page?

moulon% cat b.rb
#!/usr/bin/ruby
class TkLabel
   def text(*args)
      puts "text #{args}"
   end

   def pack(*args)
      puts "pack #{args}"
   end
end

TkLabel.new.instance_eval {
   text(1, 2)
   pack(3, 4)
}
moulon%

moulon% ./b.rb
text 12
pack 34
moulon%


Guy Decoux
Mat S. (Guest)
on 2006-05-26 18:01
(Received via mailing list)
On May 26, 2006, at 9:52 AM, ts wrote:

>>>>>> "M" == Mat S. <removed_email_address@domain.invalid> writes:
>
> M> Can you give a code example or documentation page?
>
> [code ommited]

That example wasn't quite what I meant, but I found it myself.
Incase anyone else was following and is interested, here's the sort
of syntax I was curious about:

class MyClass
   def initialize &block
     instance_eval &block
   end

   def foo
     puts "hi"
   end
end

MyClass.new { foo }

Thanks for pointing me in the right direction, Guy.
-Mat
This topic is locked and can not be replied to.