Jcm Mz wrote:
That I can see; Pragmatic Programming Ruby's, index, has reference to
all sorts of symbols, but I can't find a explanation for a ',' seperator
such as used in the following:
var1 = 1; p var1 #=> 1
var2 = 2; p var2 #=> 2
var3 = 3; p var3 #=> 3
var1, var2, var3 = 5
p var1 #=> 5
p var2 #=> nil
p var3 #=> nil
What's happening here?
It's called "parallel assignment". Here is the basic case:
x, y = 10, 20
puts x #10
puts y #20
Then there are rules for dealing with the cases when the number of
variables on the left side do not equal the number of values on the
right side. You are seeing the rule: if there are more "lvalues" than
"rvalues", the excess lvalues will have nil assigned to them.
One of the little tricks you can do with parallel assignment is switch
values in two variables without using a third variable:
str = "hello"
num = 100
str, num = num, str
puts str #100
puts num #hello
Normally, if there are more rvalues than lvalues then the excess rvalues
are discarded, for example:
x, y = 10, 20, 100, 200
puts x #10
puts y #20
But you can also do this:
x, y, *remaining = 10, 20, 100, 200
puts x #10
puts y #20
p remaining #[100, 200]
And this is also another way to do parallel assignment:
x, y, z = [10, 20, 30]
puts x #10
puts y #20
puts z #30
In pickaxe2, a detailed description of parallel assignment is on p. 340.
···
--
Posted via http://www.ruby-forum.com/\.