Symetric method calls

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?

On Dec 9, 2010, at 12:57 , Richard P. wrote:

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).

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

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

Thanks overloading the
square brackets should
do what I want. :slight_smile: