This is from something that came up in another thread.
Someone wanted to be able to overload the ‘=’ operator. There was a time
a few year back when I wanted to be able to do this as well, but now I
agree it is ill-advised and would endanger global peace (0ops, too late).
Would allowing for overloading a ‘:=’ operator break anything? (seems kind
of Pascalish
Why would you want to do this?
I’ve got a class like so:
class Ternary #can only take on values 0,1,2
def initialize(value=0)
check_value(value)
@value = value
end
def check_value(value)
if value > 3 || value < 0
raise OutOfRangeException, "value is out of range"
end
end
def :=(value) #not currently possible, but it would be cool
check_value(value)
@value = value
end
def +(value)
Ternary.new((@value + value)%3)
end
def -(value)
Ternary.new((@value - value)%3)
end
end
This would allow you to do:
b = Ternary.new
b := 2
b := 42 #raise exception
So the ‘:=’ operator ‘looks’ close enough to assignment so that the
meaning is clear and it keeps me from having to do:
b.assign 42
Which is how I do it currently with this class and several other classes
I’ve come up with over the years.
So how about it, would allowing a ‘:=’ operator break anything?
I would tend to think not as the ‘:’ appears either as ‘::’ or :symbol so
there shouldn’t be a case where ‘:’ and ‘=’ can legally appear together
now (but I could be overlooking something).
Phil