In older versions of Ruby, the return value of an assignment statement is the return value of the method that sets the property. In Ruby1.8, the value of an assignment statement is always the value of the parameter and the return value of the method is discarded.
Class Test
def val= (val)
@val = val return end
t = test.new
a = t.val=2
a -& Gt;2
In the old version, a assigns the assignment statement to 99, whereas in Ruby1.8 it has a value of 2.
Ruby's assignment is actually performed in parallel, so the value on the right side of the assignment statement is not affected by the assignment statement itself. The values on the right are computed in the order in which they appear, before any of the variables on the left or attributes are assigned. This is illustrated by this artificial design example below. The second line of expression X, X+=1 and x+=1 values are assigned to variables a, B, and C, respectively.
x = 0 -> 0
a,b,c =x, (x+=1), (x+=1) ->[0,1,2]
When an assignment statement has more than one left value, the assignment expression returns an array of the right values. If the value of the assignment statement has more left than the right, the extra left value is ignored. If the right value is an extra left value, the extra right value is ignored. If an assignment statement has only one left value and multiple right values, the right value is converted to an array and then assigned to the left value.
In fact, there is a hidden trap for writable properties. In general, a method in a class can call the other methods of the same class and the methods of its parent class in the form of a function (that is, with an implicit self as the receiver). However, this does not apply to attribute assignment functions: Ruby sees an assignment statement, it thinks that the name on the left is a local variable, not a method call that assigns the property.
Class Brokenamplifier
Attr_accessor:left_channel,: Right_channel
def volume= (vol.)
Left_channel = Self.right_channel = Vol.
end
ba = brokenamplifier.new
ba.left_channel = Ba.right_channel =99
Ba.volume=5
ba.left_channel ->99
ba.right_channel ->5
In the above assignment statement, we forgot to add "self." to Left_channel. Prefix, ruby stores the local variables for the new value to the Volume= method because the object properties are not updated at all. It's going to be an untraceable flaw.