how do i turn an object into a binding?

B

Bret Pettichord

I have code such as this:

foo.bar
foo.baz(1)
foo.bagaloo('didoo')

instead i want to write it like this:

with (foo) do
bar
baz(1)
bagaloo('didoo')
end

how?


_____________________
Bret Pettichord
www.pettichord.com
 
A

Austin Ziegler

foo.instance_eval do
bar
baz(1)
bagaloo('didoo')
end

Note that this won't work if you try to use assignment, because that
will be interpreted as a local variable. Better:

module Kernel
def with(obj)
yield self if block_given?
end
end

with longfooname do |f|
f.bar
f.baz(1)
f.bagaloo('didoo')
end

-austin
 
F

Florian Frank

Austin said:
Note that this won't work if you try to use assignment, because that
will be interpreted as a local variable.
True. In this case 'self' could be used:

foo.instance_eval do
self.quux = true
end

If assignment methods haven't yet been defined in a class definition,
the same problem occurs.
Better:

module Kernel
def with(obj)
yield self if block_given?
end
end

with longfooname do |f|
f.bar
f.baz(1)
f.bagaloo('didoo')
end

-austin
Well, than you could do f = longfooname at the beginning as well. ;)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,166
Messages
2,570,902
Members
47,443
Latest member
RobertHaddy

Latest Threads

Top