with block in ruby

R

Robert Klemme

is there any way in ruby to do something like:

with thisobject do
=A0....


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
=3D> 3

Or you can use #tap (1.9)

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

Cheers

robert

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
 
H

Haruka YAGNI

Do you mean something like this?

def with(arg)
yield arg
end

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


is there any way in ruby to do something like:

with thisobject do
=A0....


end



--=20
Haruka YAGNI
(e-mail address removed)
 
A

Adam Prescott

[Note: parts of this message were removed to make it a legal post.]

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
 
X

Xavier Noria

is there any way in ruby to do something like:

with thisobject do
=C2=A0....


end

Yes, you can accomplish that with instance_eval:

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

with [] do
p length # =3D> 0
end

-- fxn
 
B

botp

try #instance_eval

eg,

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

with "test" do
puts capitalize
end
Test

best regards -botp
 

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,430
Messages
2,571,676
Members
48,796
Latest member
Greg L.

Latest Threads

Top