From: daz Date: 2003-09-13T21:40:34+09:00 Subject: Re: order of evaluation for method arguments "Michael Garriss" wrote: > Michael Garriss wrote: > > > Is this code guaranteed to always work this way: > > > > a = [1,2,3,4,5] > > --> [1, 2, 3, 4, 5] > > def m( a, b, *c ) > > puts a, b, c > > end > > --> nil > > m( a.shift, a.shift, a ) > > 1 > > 2 > > 3 > > 4 > > 5 > > --> nil > > > > I'm wondering (hoping) that the arguments will always be evaluated > > from left to right as is the case above. Is this a 'ruby rule' or > > something that could change? > > From Pickaxe: The Ruby Language Method Definition Method Arguments (I can't find this section on rubycentral/book to link to) "The expressions are evaluated from left to right. An expression may reference a parameter that precedes it in the argument list." #-------------------- a = [1,2,3,4,5] def m( a, b, *c ) p a, b, c end m( a.shift, b=a, a ) #-------------------- #-> 1 #-> [2, 3, 4, 5] #-> [[2, 3, 4, 5]] So that's as safe as Pickaxe. > > Let me extend the question to include arrays (which might > be related to arguments, I don't know, I've never looked > at the ruby source): > > a = [1,2,3,4,5] > --> [1, 2, 3, 4, 5] > b = [a.shift,a.shift,a.shift,a.shift,a.shift] > --> [1, 2, 3, 4, 5] > Well, since: a, b = b, a is 'defined' (in the sense that it's a ruby idiom), your example works the way I'd expect, even though Matz has guarded his options. Perhaps he means that this could look like a prime candidate for optimization which would give [1, 1, 1, 1, 1] but I don't know if anyone would like to see that happen. > > Michael > daz