Equivalent of const modifier

E

eastcoastcoder

Very often, I'd like to ensure (and document) that a method will not
change any of its parameters:

# This looks at, but doesn't modify, a and b
def mymethod(a, b)
end

In C++ I can do this with the const modifier.

Is there anyway to do this in Ruby?

I'd call freeze, except that would freeze the original a as well.
I'd call dup/clone and then freeze, but those aren't deep copies, from
what I understand.

So, I guess my question boils down to:
Is there a way to make a frozen, full (ie deep) copy of an object?
 
D

David Vallner

D=C5=88a Nede=C4=BEa 12 Febru=C3=A1r 2006 22:18 (e-mail address removed) na=
p=C3=ADsal:
Very often, I'd like to ensure (and document) that a method will not
change any of its parameters:

The most Ruby way would be plain not changing the parameters - you're=20
perfectly sure the method doesn't do that when it doesn't do that. Quoting=
=20
James Britt from a recent post: "Ruby assumes the developer is a grown-up."

Also, I believe the convention would be that a method doesn't clobber its=20
parameters unless -that- is explicitly documented, so I wouldn't go out of =
my=20
way to document that a method does -not- change its parameters.
# This looks at, but doesn't modify, a and b
def mymethod(a, b)
end

In C++ I can do this with the const modifier.

Well, with the risk of stating the obvious, Ruby isn't C++. Some things are=
=20
plain done differently. Or not at all.
Is there anyway to do this in Ruby?

I'd call freeze, except that would freeze the original a as well.
I'd call dup/clone and then freeze, but those aren't deep copies, from
what I understand.

So, I guess my question boils down to:
Is there a way to make a frozen, full (ie deep) copy of an object?

Implement #initialize_copy for deep-copy semantics, override #freeze to fre=
eze=20
instance attributes of the object before.

I wouldn't bother though, as far as I know, freezing objects is only used w=
hen=20
debugging, e.g. when you suspect a bug is due to an object being changed=20
someplace you don't expect it. It's not encouraged for use in common code=20
unless necessary.

David Vallner
 
D

David Vallner

D=C5=88a Pondelok 13 Febru=C3=A1r 2006 21:38 Adam P. Jenkins nap=C3=ADsal:
Unless your code is multithreaded, you could always just unfreeze the
arguments when the function exits, since nothing else will be accessing
the objects while mymethod is executing.

I thought freezing objects was permanent?

David Vallner
 

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

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,119
Latest member
IrmaNorcro
Top