Mark Bush wrote:
James Britt wrote:
Suppose secret_code=(x) checks that the given value meets some criteria
(say, is a positive int), and if not, uses the value 0. I might want
the method to then return a valid value, not simply what was passed in.
If the setter is called in an assignment context, the assignment will always return the rhs regardless of what the setter returns. This is for compatibility as Ezra pointed out.
Compatibility with *what*? Not with how other methods behave.
It's a cultural thing.
If you do:
a = b = c = 3
what's the value of a? You would expect it to be 3.
Perhaps. Depends on the language. But let's assume so.
What about:
a = b.bar = c = 3
What is a now? Again, wouldn't you still be hoping it would be 3?
No.
Depends on b. Maybe 3 is not a valid argument for whatever bar does.
I expect that if I'm involving an object then that object may have its own ideas about how to handle the request. That's sort of their job.
Assignment is a syntactic construct.
Assignment creates or changes a variable binding.
"b.bar = 3" is not a method call, it's an assignment.
b.methods.include?( 'bar=' )
def b.bar=( arg )
exit if arg % 2 == 0
end
Pedantic, sure, but believing that "=" always means a setter method, or is altering an attribute named in the message, is a mistake. It's seems mainly to be a convenience for people who like to think in terms of getters and setters rather than pure messages and private attributes.
It's handy, but a little heavy-handed.
Here's a less churlish example:
def b.bar=(x)
@bar = x.to_i.abs
end
Sadly, this will not return the value of @bar.
Most people don't have a problem with this, and I suspect that was a reason matz made Ruby behave this way. But it seems to impede a broader understanding of how Ruby works (and maybe that is part of the reason some folks misuse, for example, open classes.)
It's a trade-off.
> Part of evaluating that assignment involves
invoking a method, but, by definition,
The definition comes first, and can be otherwise.
assignment returns the rhs, so whatever happens with any method so invoked, its value is lost.
As so behaviorally defined in Ruby for methods of a certain form. It breaks the simpler concept of all object interaction being done with messages, and all methods returning the value of the last executed expression.
But, again, this is PO(matz)LS. I think I understand why matz choose it, but it was a matter of taste, not immutable laws of computer science.
···
--
James Britt
"The use of anthropomorphic terminology when dealing with
computing systems is a symptom of professional immaturity."
- Edsger W. Dijkstra