Re: How to define the assignment operator in Ruby ?
On Feb 21, 4:55 am, Stephane Wirtel <stephane.wir...@descasoft.com>
wrote:
> Hi all,
>
> How to define the assignment operator for a class ?
>
> irb(main):012:0> class Test
> irb(main):013:1> def = other
> irb(main):014:2> puts other.class
> irb(main):015:2> end
> irb(main):016:1> end
> SyntaxError: compile error
> (irb):13: syntax error, unexpected '='
> def = other
> ^
> (irb):16: syntax error, unexpected kEND, expecting $end from (irb):16
>
> Is there a way to solve my issue ?
>
> Where is my mistake ?
>
> I don't believe that's possible to assign something to an instance
>
> Best Regards,
>
> Stephane
Stephane,
What exactly are you trying to do? If you are trying to implement a
method that copies an object, this is supported in the language via
the dup() or clone() methods:
str = "I am a string."
copy_of_str = str.clone
str.object_id should not equal copy_of_str.object_id
For your own objects, the default clone and dup methods perform
shallow copies of state (references are copied). You would have to
override clone or dup to do anything more complicated.
class A
attr_accessor :str
def initialize(str)
@str = str
end
end
a = A.new("test")
b = a.clone
a.object_id != b.object_id
but
a.str.object_id == b.str.object_id
Is this what you were getting at?
-Doug
|