Symetric method calls

R

Richard Price

I would like to define two methods in a class
such that they could be called as follows

value = obj.meth1(a,b)

obj.meth2(a,b) = value

I can code the first [accessor] method easily as

def meth1(a,b)

but how do I code the def statement for the second
[setter?] method?
 
R

Ryan Davis

I would like to define two methods in a class
such that they could be called as follows
=20
value =3D obj.meth1(a,b)
=20
obj.meth2(a,b) =3D value
=20
I can code the first [accessor] method easily as
=20
def meth1(a,b)
=20
but how do I code the def statement for the second
[setter?] method?

It is not possible in ruby to assign to a local variable to the right of =
an assignment (as written above).
 
N

Nathan Clark

I'm not sure if such a method can be created, but you wouldn't be able
to call it anyway; foo.meth(...) = ... is a syntax error, regardless
of the parameters or right hand side of '='.

An alternative could be to have meth2(a,b) return a container for the
value you're wanting to set, and use:

foo.meth2(a, b).value = value

where .value is a method on the container object returned by meth2.

While () = is a syntax error, you can use [] =, by overloading the
square brackets, if that does what you want.

e.g.

def [](a,b)
# return the value at that index
end

def []=(a,b)
# set the value at that index
end

Then use it like:
foo[:fizz, :buzz]
=> nil

foo[:fizz, :buzz] = 42
=> 42

foo[:fizz, :buzz]
=> 42
 

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,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top