With block in ruby

is there any way in ruby to do something like:

with thisobject do

end

On Mon, Mar 28, 2011 at 5:05 PM, Mario R. [email protected] wrote:

is there any way in ruby to do something like:

with thisobject do

end

Depends on what you want to do, probably use #instance_eval e.g

irb(main):001:0> “foo”.instance_eval do p size end
3
=> 3

Or you can use #tap (1.9)

irb(main):002:0> “foo”.tap do |x| p x.size end
3
=> “foo”

Cheers

robert

On Mon, Mar 28, 2011 at 4:05 PM, Mario R. [email protected] wrote:

is there any way in ruby to do something like:

with thisobject do

end

You could use

obj.instance_eval do
puts self.inspect
end

or:

obj.instance_eval do |something|
puts something.inspect
end

On Mon, Mar 28, 2011 at 5:05 PM, Mario R. [email protected] wrote:

is there any way in ruby to do something like:

with thisobject do

end

Yes, you can accomplish that with instance_eval:

def with(obj, &block)
  obj.instance_eval &block
end

with [] do
  p length # => 0
end

– fxn

Do you mean something like this?

def with(arg)
yield arg
end

with [1,2,3] do |i|
p i.size # => 3
end

try #instance_eval

eg,

def with o, &block
o.instance_eval &block
end
#=> nil

with “test” do
puts capitalize
end
Test

best regards -botp

On Mon, Mar 28, 2011 at 5:13 PM, Robert K.
[email protected] wrote:

Or you can use #tap (1.9)

Also available in 1.8.7 :).

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs