With statement

I’m pretty sure ruby doesn’t have a with statement. Is it possible to
emulate one?

On Jan 4, 11:51 am, ole __ [email protected] wrote:

I’m pretty sure ruby doesn’t have a with statement. Is it possible to
emulate one?

Yes:

module Kernel
def with(obj, &b)
obj.instance_eval(&b)
end
end

Usage:

class Foo
def dostuff
puts “doing stuff in Foo”
end
end

foo = Foo.new

with foo do
dostuff
end

Rgds,
Lars

Lars wrote:

On Jan 4, 11:51 am, ole __ [email protected] wrote:

I’m pretty sure ruby doesn’t have a with statement. Is it possible to
emulate one?

Yes:

Or

class Object
def with(&b)
instance_eval(&b)
end
end

#Usage:

class Foo
def dostuff
puts “doing stuff in Foo”
end
end

foo = Foo.new

foo.with do
dostuff
end

Tiziano

On Jan 4, 2008, at 5:51 AM, ole __ wrote:

I’m pretty sure ruby doesn’t have a with statement. Is it possible to
emulate one?

Posted via http://www.ruby-forum.com/.

Maybe. You’re not very clear on what semantics you expect from
‘with’. But you might try

alias with instance_eval

Then you can write stuff such as:

obj.with do
foo
bar
end

in place of

obj.foo
obj.bar

Regards, Morton

Great solutions thanks guys.
I think I’m going to go with the…

with obj do
method_from_obj
end

…one because it reads better as English.

If you get my gem utility_belt, it has a with statement by Dan Y.
in it. This thread came up about a month ago here. Weird to think that
this is a FAQ.

On 1/4/08, ole __ [email protected] wrote:


Giles B.

Podcast: http://hollywoodgrit.blogspot.com
Blog: http://gilesbowkett.blogspot.com
Portfolio: http://www.gilesgoatboy.org
Tumblelog: http://giles.tumblr.com